首页 > 解决方案 > 如何在 Parent 的孩子中使用 ref 访问 Child - React@latest

问题描述

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

我们将所有其他组件分组的主要组件:

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

目标是创建对每个in或每个in或 even的引用,所以让我们进一步了解组件,现在 Form 和 FormGroup 是渲染子组件的空组件:TextInputFormGroupRadioButtonRadioGroupFormGroup

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

标签: reactjsparent-childreact-propsref

解决方案


如果您正在使用表单,我建议您使用 react-hook-form。 反应挂钩形式


推荐阅读