如何在父母的孩子中访问带有参考的孩子 - React@latest

问题描述 投票:0回答:1

这个代码示例是对结构的最小化表示

主要组件,我们将所有其他组件分组。

<Form>
   <FormGroup>
       <RadioGroup>
           <RadioButton/>
           <RadioButton/>     
       </RadioGroup>
   </FormGroup>
   <FormGroup>
       <TextInput />
   </FormGroup>
   <Button>Submit Form</Button>
</Form>

我们的目标是创建一个 参考 对每一个 TextInputFormGroup 或对每个 RadioButtonRadioGroup 甚至 FormGroup,所以让我们再往下看组件,目前Form和FormGroup是空的组件,渲染子组件。

const Form: React.FunctionComponent<Props> = ({ children }) => {
    return (
      <form>
          {children}
      </form>
  );
};
const FormGroup: React.FunctionComponent<Props> = ({ children }) => {

  // WE WANT TO ACCESS REF HERE, with React.Children.map every child's ref is always null

  return (
     {children}
  );
};

为了简单起见 RadioGroup 也只是呈现出孩子

const RadioGroup: React.FunctionComponent<Props> = ({ children }) => {

  // WE WANT TO ACCESS REF HERE, with React.Children.map every child's ref is always null

  return (
     {children}
  );
};

我们正在进入正题,我们要创建一个引用的Child,在这个例子中是 RadioButton 组成部分

class RadioButton extends Component<{props}, state> {
  this.state = {
      inputRef: React.createRef()
  };

  handleClick() {
   WE CAN ACCESS THE REF HERE
   // this.state.inputRef.current
  }

  render() {
    return (
      <div> // putting the ref here also doesnt work in parent components
         <label>
           <input 
               ref={this.state.inputRef} 
               onChange={() => this.handleClick()}
           />
         </label>
      </div>
    );
  }
};
reactjs parent-child react-props ref
1个回答
0
投票

如果你使用form,我建议你使用react-hook-form。react-hook-form

© www.soinside.com 2019 - 2024. All rights reserved.