【问题标题】:How to access Child with ref in Parent's children - React@latest如何在 Parent 的孩子中使用 ref 访问 Child - React@latest
【发布时间】:2020-06-03 15:18:57
【问题描述】:

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

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

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

目标是为FormGroup 中的每个TextInputRadioGroup 甚至FormGroup 中的每个RadioButton 创建一个引用,所以让我们进一步了解组件,目前 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】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-09-15
      • 2021-08-20
      • 1970-01-01
      • 2015-03-08
      • 2020-04-28
      • 2016-03-22
      • 1970-01-01
      相关资源
      最近更新 更多