如何使用 Parent 的 children 中的 ref 访问 Child - React@latest

How to access Child with ref in Parent's children - React@latest

此代码示例是结构的最小表示

我们对所有其他组件进行分组的主要组件:

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

目标是为 FormGroup 中的每个 TextInputRadioGroup 中的每个 RadioButton 创建一个 reference甚至 FormGroup,所以让我们进一步深入组件,现在 Form 和 FormGroup 是空组件呈现 children:

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 也只是渲染 children

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>
    );
  }
};

如果您正在使用表单,我建议您使用 react-hook-form。 react-hook-form