1

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

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

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.tex的handleClick方法中执行此操作,但显然无法正常工作。

谢谢!

4

3 回答 3

0

通过回调传递tex道具:SubComp

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

handleClick并在of 中使用它MyComponent

handleClick(tex) {
  this.setState({name: tex});
}
于 2020-12-22T21:17:25.080 回答
0

您还可以转换SubComp为功能组件并将其传递给handleClick您在内部定义MyComponent的道具:

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

然后像这样传递它的handleClick方法:<SubComp handleClick={this.handleClick} />

于 2020-12-22T21:26:15.893 回答
0

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

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

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

于 2020-12-22T21:07:01.677 回答