首页 > 解决方案 > 新的反应学习者

问题描述

我正在学习 react 并且一直在 Codecademy 上一门课程。现在我自己玩,只是想捡东西。

假设我保存了一些列表。例如

我有一个父页面。我希望用户能够搜索处于某个状态或邮政编码等的运动员。

有人可以指出我正确的开始方向。我猜我需要使用道具。如果陈述或类似的东西,但现在是新的,这一切都让人难以抗拒。

如果有人可以帮助我开始或指出我可以获得更多信息的方向,那就太好了。

标签: reactjscomponents

解决方案


您有一个从用户获取搜索输入值并将搜索值传递给子组件的父组件。

class Parent extends Component {

  state = {
    state: '',
    postal: ''
  }

  // Search terms from the user
  // You decide how you should get these values
  search(state, postal) {
    this.setState({ state, postal })
  }

  render() {
    return (
      <div className="App">
        {/* Pass your search terms to your child */}
        <MyChild state={ this.state.state } postal={ this.state.postal } />
      </div>
    );
  }
}

子组件将通过 props 获取这些搜索值,并检查它们是否存在于您定义的列表中。

class Child extends Component {

  constructor(props) {
    super()
  }

  // check if item exists in list
  check() {
    // Get props
    const { state, postal } = this.props
    // Search through list
    return list.find(item => {
      if (state === item.state) { return item.name }
      if (postal === item.postal) { return item.name }
    })
  }

  render() {
    return (
      <div>
        // render the name of the athelete
        <p>{ this.check() }</p>
      </div>
    );
  }
}

推荐阅读