【问题标题】:React access sub-components properties in main componentReact 访问主组件中的子组件属性
【发布时间】:2020-12-23 05:26:15
【问题描述】:

是否可以在 React 中访问主组件中的子组件属性?

例如我正在尝试这个:我有一个主组件 MyComponent 和一个呈现按钮的 SubComp 子组件。是否可以将 MyComponent 的状态设置为等于单击的 SubComptex 属性?

class MyComponent extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      name: 'Initial State'
    };
    this.handleClick = this.handleClick.bind(this);
  }
  handleClick() {
    this.setState({name: SubComp.tex});
  }
  render() {
    return (
      <div>
        <SubComp onClick={this.handleClick} tex="but1"/>
        <SubComp onClick={this.handleClick} tex="but2"/>
        <h1>{this.state.name}</h1>
      </div>
    );
  }
};

class SubComp extends React.Component {
  constructor(props){
    super(props);
  };
  render(){
    return(
      <button onClick={this.props.onClick}>Click Me</button>
    );
  }
}

我尝试在 SubComp.texhandleClick 方法中执行此操作,但显然不起作用。

谢谢!

【问题讨论】:

    标签: reactjs


    【解决方案1】:

    通过回调传递SubComp 中的tex 属性:

    render() {
      return (
        <button onClick={() => this.props.onClick(this.props.tex)}>Click Me</button>
      );
    }
    

    并在MyComponenthandleClick中使用:

    handleClick(tex) {
      this.setState({name: tex});
    }
    

    【讨论】:

    • 当客!现在根据需要工作
    【解决方案2】:

    是的,这绝对是可能的。您从主组件传递函数的想法是正确的,但要实现您想要做的事情,您可以将参数传递给函数,如下所示:

      handleClick(e) {
        this.setState({name: e.target.value});
      }
    

    请注意,我已将e 作为参数添加到您的handleClick 函数中。这是通过单击按钮接收到的单击事件。然后我们将状态设置为等于该事件的值。

    【讨论】:

      【解决方案3】:

      您还可以将SubComp 转换为功能组件,并将您在MyComponent 中定义的handleClick 作为道具传递:

      const SubComp = ({handleClick}) => {
        return <button onClick={handleClick}>Click me</button>
      }
      

      然后像这样传递它的handleClick方法:&lt;SubComp handleClick={this.handleClick} /&gt;

      【讨论】:

        最近更新 更多