在React中,要获取兄弟组件的子组件的值,可以通过使用Refs来实现。

首先,在兄弟组件的父组件中创建一个Refs对象。例如:

class ParentComponent extends React.Component {
  constructor(props) {
    super(props);
    this.childRef = React.createRef();
  }

  render() {
    return (
      <div>
        <SiblingComponent ref={this.childRef} />
        <button onClick={this.handleClick}>获取子组件的值</button>
      </div>
    );
  }

  handleClick = () => {
    const childComponent = this.childRef.current;
    const childValue = childComponent.getChildValue();
    console.log(childValue);
  };
}

然后,在兄弟组件中,使用forwardRef函数将子组件传递给父组件,并在子组件中定义一个方法来获取子组件的值。例如:

const SiblingComponent = React.forwardRef((props, ref) => {
  const inputRef = React.useRef();

  React.useImperativeHandle(ref, () => ({
    getChildValue: () => {
      return inputRef.current.value;
    }
  }));

  return <input ref={inputRef} />;
});

通过上述代码,当点击父组件中的按钮时,会调用子组件的getChildValue方法来获取子组件中输入框的值,并将其打印到控制台中

react获取兄弟组件的子组件里面的值

原文地址: http://www.cveoy.top/t/topic/ivr5 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录