如何在渲染函数中检查 react 中子组件的状态

How to check state of a child component in react in render function?

本文关键字:react 组件 状态 检查 函数      更新时间:2023-09-26

我正在渲染两个组件SearchForm和RecentSearch,例如

var SearchFormContainer = React.createClass({
  render: function() {
    return (
        <div>
        <SearchForm />
        <RecentSearch />
        </div>      
    );;
  }
});

搜索表单中有一个状态。根据我想呈现最近搜索组件的状态。如何查看搜索源的状态?我尝试的是:

var SearchFormContainer = React.createClass({
  render: function() {
    return (
        <div>
        <SearchForm ref="search_form"/>
        {this.refs.search_form.state ? <RecentSearch /> : null}
        </div>
    );
  }
});

this.refs.search_form.状态重构未定义。

将状态保留在父容器中 ( SearchFormContainer (。更新此状态,例如通过传递给SearchForm的回调函数。像这样:

const Container = React.createClass({
  onSearch(value) {
    this.setState({search: value});
  }
  render() {
    <div>
      <SearchForm onSearch={this.onSearch} />
      <RecentSearch recentValue={this.state.search} />
    </div>
  }
});
const SearchForm = ({onSearch}) => {
  return (
    <input
      type="search"
      onChange={event => onSearch(event.target.value)}
    />
  );
}

我也推荐Dan Abromov关于Smart&Dumb Components的文章:https://medium.com/@dan_abramov/smart-and-dumb-components-7ca2f9a7c7d0#.qq4cufc2c

希望这有帮助!

在 React 中,状态是一个组件级的概念,它通过将 props 传递给子组件从上到下工作,而不是相反。

如果要根据SearchForm的状态渲染RecentSearch组件,则可以向SearchFormContainer组件添加额外的状态层,该状态基本上跟踪SearchForm提交并基于此有条件地呈现RecentSearch

var SearchFormContainer = React.createClass({
  getInitialState: function() {
    return { userHasSearched: false }
  },
  onSearchSubmit: function() {
    this.setState({ userHasSearched: true });
  },
  render: function() {
    return (
      <div>
        //Pass submit handler down to the SearchForm component
        <SearchForm onSubmit={this.onSearchSubmit} />
        {this.state.userHasSearched ? <RecentSearch /> : null}
      </div>
    );
  }
});

或者更好的是,消除引入的额外复杂性(除非您对SearchFormContainer有特定的未来意图(,并且只需在 <SearchForm /> 中有条件地返回您的<RecentSearch />组件,您的状态目前实际位于该位置。