【问题标题】:React: setting state in container from within functional componentReact:从功能组件中设置容器中的状态
【发布时间】:2016-10-14 20:21:59
【问题描述】:

所以我有一个容器组件,它与其他一些 JSX 一起呈现一个功能组件。我正在尝试通过从该功能组件内部发生的按钮单击来更改该容器中的状态。但是我还没有找到解决这个问题的好文章,我遇到了this.setState() is not a function 的问题,或者我通过尝试trigger a setState call during a render(或多或少)完全打破了当前标签。

这里有一些示例代码来说明我的意思:

class TestComponent extends Component {
  render() {
    <div>
      <FunctionalComponent close={(type) => this.setState({ property: type })} />
    </div>
  }
};

功能组件:

const FunctionalComponent = (props) => {
  return (
    <button onClick={props.close('stringvalue')}>Click to setState</button>
  );
};

还尝试在容器内创建一个单独的函数并从那里调用this.setState(),但问题仍然存在。这是上下文问题吗?

【问题讨论】:

    标签: javascript reactjs components


    【解决方案1】:

    更地道一点。 . .

    class TestComponent extends Component {
      constructor(props) {
        super(props);
        this.onClose = this.onClose.bind(this);
      }
    
      onClose(property) {
        this.setState({ property })
      }
    
      render() {
        return (
          <div>
            <FunctionalComponent close={this.onClose} />
          </div>
        )
      }
    };
    
    const FunctionalComponent = ({ close }) => {
      return (
        <button onClick={close.bind(null, 'stringvalue')}>Click to setState</button>
      );
    };
    

    【讨论】:

      【解决方案2】:

      我认为问题在于您的 props.close 函数在每次渲染时都会被调用,因为您没有传递函数而是调用它。

      onClick 需要一个函数。

      const FunctionalComponent = (props) => {
        function onClick() {
          props.close('stringvalue');
        }
        return (
         <button onClick={onClick}>Click to setState</button>
        );
      };
      

      const FunctionalComponent = (props) => {
        return (
         <button onClick={() => props.close('stringvalue')}>Click to setState</button>
        );
      };
      

      【讨论】:

        猜你喜欢
        • 2021-04-17
        • 1970-01-01
        • 2020-08-23
        • 2020-05-07
        • 1970-01-01
        • 2020-11-18
        • 2020-10-15
        • 2021-03-23
        • 2021-10-08
        相关资源
        最近更新 更多