簡體   English   中英

反應:從功能組件內部在容器中設置狀態

[英]React: setting state in container from within functional component

因此,我有一個容器組件,該組件與其他一些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() ,但是問題仍然存在。 這是上下文問題嗎?

有點慣用了。

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>
  );
};

我認為問題在於您在每個渲染器上調用了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>
  );
};

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM