如何将子组件中的参数传递给2级

时间:2017-05-17 05:30:13

标签: javascript reactjs

我是React的新手并且遇到了一个场景,我有一个来自父级的二级子结构。在级别2,存在子组件的动态列表,并且每个子组件具有关联的复选框。那么我如何在这个孩子的onChange事件中将一些数据(比如假设水果名和id)传递给父母。

3 个答案:

答案 0 :(得分:0)

下面是我的动作类,我已经定义了函数和  如果需要函数被称为

,将采取什么行动
 import Dispatcher from "./Dispatcher.jsx";
export function createTodo(text)
{

Dispatcher.dispatch(
{

type: "CREATE_TODO",
text

}
);


}

这是我的商店组件,它接收调度员的行动

import {EventEmitter} from 'events';
import React from 'react';
import Dispatcher from "./Dispatcher.jsx";
class TodoStore extends EventEmitter
{
constructor()
{
super();
this.todos=[



        ]
            }

            createNewTodo(text)
            {

                const id=Date.now();
                this.todos.push({
                    id,
                    text,
                    company:"Ibm"
                });
                this.emit("change");

            }

            getAll()
            {
            return this.todos;
            }

            handleActions(action)
            {
                console.log("todostore receied an action",action);
                switch(action.type)
                {
                case "CREATE_TODO":
{

                    this.createNewTodo(action.text);
                }


                }



            }


}

这是在todoActions组件中调用函数createTodo(text)的Featured类。

然后将在todoActions类中触发操作,并且调度程序将调度该操作,并且在存储组件事件发生器中的事件更改发出更改事件,并且此事件将被捕获到特色组件中,因此必需的参数将传递给此类。

import React from 'react';
import { Link } from "react-router";
import {Button, IconButton} from 'react-toolbox/lib/button';
import Input from 'react-toolbox/lib/input';
import Todo from "./Todo.jsx";
import TodoStore from "./Store.jsx";
import injectTapEventPlugin from 'react-tap-event-plugin';
import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider';
import RaisedButton from 'material-ui/RaisedButton';
import * as todoActions from "./todoActions.jsx";





class Featured extends React.Component {
    constructor()
    {

        super();

        this.state=
        {
        todos:TodoStore.getAll()


        }

    }
    componentDidMount()
    {


    alert("after")
    }
    componentWillMount()
    {
        alert("before")


        TodoStore.on("change",()=>{
            this.setState({
                todos:TodoStore.getAll()
            });
        });
    }
    createTodo()
    {

        todoActions.createTodo(Date.now());

    }
    reloadTodo()
    {

        todoActions.reloadTodo();

    }
   render() {



      return (
      <MuiThemeProvider>
      <div>






      <h1>Featured</h1>
      <Button label='Create' accent onClick={this.createTodo.bind(this)}/>

      <table>
       <tbody>{this.state.todos.map((todo, i) => <Todo key={i} todos= {todo} />)}</tbody>
     </table>
      </div>
      </MuiThemeProvider>
      );
   }
}


export default Featured;

答案 1 :(得分:0)

一种方法是将回调作为道具传递给组件。

与父组件类似,创建处理程序:

//keep descriptive name so you can remember later on 
handleChangeInChild2(event) {
    console.log("name:", event.target.name, ", val=", event.target.value)
    //do your stuff
}

render() {
    //sending the handler function to first child as a callback
    return <Child1 handler={this.handleChangeInChild2.bind(this)}/>
}

在Child1的渲染中,从道具中挑选并按原样发送给child2

render() {
    return <Child2 handler={this.props.handler}/>
}

在最终的child2渲染中,您现在可以在INPUT上安装处理程序

render() {
    return <input type="checkbox" onChange={this.props.handler}/>
}

答案 2 :(得分:0)

您需要将一个函数作为从父级到子级的道具传递,可以更改父级的状态(假设数据存储在父级状态中,那么您可以传递包含setState的函数)

以下是一些例子:

class Parent extends React.Component {
  constructor(props) {
    this.state = {
      data: {}
    };
    this._transferData = this._transferData.bind(this); // Don't forget to bind the function to the component
  }

  _transferData(value, checked) {
    /*
      This is the function that accept values and
      pass it to the state
     */
    let data = {...this.state.data};
    data[value] = checked;
    this.setState({
      data: data
    });
  }

  render() {
    return (
      <Child1 onChange={this._transferData} />
      {/* The parent passes _transferData as a props for Child1 */}
    )
  }
}

class Child1 extends React.Component {
  render() {
    return (
      <Child2 onChange={this.props.onChange} />
      {/* Child2 passes the passed function from Parent as a props (again) for Child2 */}
    )
  }
}

class Child2 extends React.Component {
  constructor(props) {
    this.state = {
      checked: false
    };
    this._handleChange = this._handleChange.bind(this); // Don't forget to bind the function to the component
  }

  _handleChange(event) {
    this.setState({
      checked: event.target.checked
    });
    /*
      Then Child2 uses the function to update the Parent's state
     */
    this.props.onChange(event.target.value, event.target.checked);
  }

  render() {
    return (
      <form>
        <input
          type="checkbox"
          name="fruit"
          value="Apple"
          checked={this.state.checked}
          onChange={this._handleChange}
        /> I have an apple
      </form>
    )
  }
}