【问题标题】:React; parent taking input data from child反应;父母从孩子那里获取输入数据
【发布时间】:2016-09-03 00:17:58
【问题描述】:

我正在使用 React 制作一个应用程序,它从下拉菜单中获取用户输入,根据输入值进行 api 调用并显示结果。组件的结构是这样的。

Search
    Input
    Result

所以,SearchInputResult 组件的父级。我想将值从Input 传递到调用发生的Search。然后将调用结果传递给Result(令人惊讶)。

我可以在Search 中为 api 调用硬编码值,结果显示正常。

但我无法弄清楚如何将输入字段的值从Input 传递到Search。我想我应该从Search 访问子(输入)道具,但我不知道如何设置它们,因为你不打算让组件设置它自己的道具。

我知道这是错误的,但我目前的情况是:

let Input = React.createClass ({

  componentDidMount(){
    this.props.genre = this.refs.genre.value;
    // or this.state.genre = this.refs.genre ? 
  },

  render() {
      return <div>
      <select ref="genre">
        <option value="28">Action</option>
        <option value="12">Adventure</option>
        <option value="16">Animation</option>
        <option value="35">Comedy</option>

        <option value="37">Western</option>
      </select>

      <select>
       <option ref="rating" type="text" placeholder="Rating"/>
      </select>

      <select>
       <option ref="type" type="text" placeholder="Type"/>
      </select>

       <input type="submit" value="Submit"/>
     </div>
    }
});

export default Input;

Search

let Search = React.createClass ({
  getInitialState(){
    return {
      movies: ['Men In Black']
    };
  },

  componentDidMount(){

    let genre = this.props.genre || '';
    let url   = `http://theapi.org/3/discover/movie?${key}&with_genres=${genre}`;
    Request.get(url).then((response) => {
      console.log('response.body.results', response.body.results)
      this.setState({
        movies: response.body.results.map(function(movie){
          return movie.title
        })
      });
    });
   },

  render(){
      console.log(this.state.movies)
      return (
        <div>
          <Input/>
          <ul>
            {this.state.movies.map( function(movie){
              return <Results key={movie.id} data={movie}/>;
            })}
          </ul>
         </div>
      );
   }
 });

 export default Search;

我希望你能看到我在这里尝试做的事情。感觉并不难,但是我对 React 的 props 和 state 的掌握是基本的,即使在阅读了文档之后我也需要一些解释。

我想我的问题是,我是否应该将数据分配给孩子的道具或状态,以及如何从父母那里访问它?

【问题讨论】:

标签: javascript reactjs input parent-child


【解决方案1】:

请记住,当您创建像 Input 这样的子组件时,它是否需要跟踪组件内的状态?如果没有,则不需要在子组件中调用 componentDidMount。只需将它的值传递给子组件内的父级,如下所示

let Input = React.createClass ({

selectHandler(){ this.props.cb(value) } 

render() {
  return <div>
  <select onClick ={this.selectHandler.bind(this)} ref="genre">
    <option value="28">Action</option>
    <option value="12">Adventure</option>
    <option value="16">Animation</option>
    <option value="35">Comedy</option>

    <option value="37">Western</option>
  </select> ........

【讨论】:

  • 嘿,谢谢@slopeofhope,但是 value 属性中的数字如何从 select 选项进入回调函数(在 selectHandler 内部)?目前我收到一条错误消息,提示值未定义,如果我在一个值中硬编码,则错误提示 cb 不是函数。
  • 那么请遵循 brett thom 的其余示例。同样要检索值,您可以执行 { this.props.cb(this.refs.genre.value)}
  • 非常感谢@slopeofhope 使用this.refs.genre.value 工作。现在我成功地将我需要的信息传递给父组件。然而,我做的一件不同的事情是添加一个button 元素并将onClick{this.selectHandler}(没有.bind(this))放在那里。所以我可以在单击按钮时将多个&lt;select&gt; 值作为参数传递给selectHandler。谢谢大家!
【解决方案2】:

您可以使用像https://github.com/reflux/refluxjshttps://github.com/reactjs/redux 这样的通量方法作为最佳方法。另一种方式,即使更丑,也可以将函数作为道具传递。

例如添加这样的东西来搜索

callBackExample(value) {
    this.setState({value: value});
},

render() {
    ...
    <Input cb = {this.callBackExample.bind(this} />
    ...
}

那么输入就可以用这个了

this.props.cb(value)

将值传回

【讨论】:

    【解决方案3】:

    此方法有效:

    1. 在父级中创建一个方法。该方法必须改变父级的状态 父母。
    2. 将该方法作为道具传递给孩子。将子状态传递给那个 方法。

    3. 当方法被调用时,它会接受子状态 作为参数,但会改变父级的状态。

      即子状态 被发送到父状态。

    现场演示:https://zly8w2xp33.codesandbox.io/

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-09-26
      • 2022-08-10
      • 2017-05-31
      • 1970-01-01
      • 2019-09-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多