在React.js中从子级到父级获取数据

时间:2018-07-06 18:33:09

标签: javascript reactjs react-redux

我正在制作一个简单的ToDo列表,并希望将数据从子ToDos组件传递到父Container组件。我目前的工作方式有效,但是我希望能够访问在Todos组件中使用的key属性,以便我可以简单地使用其值(索引)从父级数组中进行拼接。如何访问父key组件的ToDos中定义的Container属性?

const ToDos = (props) => {
  let todos = props.todos.map((value,index) => {
    return <li key={index} onClick={props.onClick}>{value}</li>
  });
  return <ul>{todos}</ul>
};

class Container extends React.Component {
  constructor(props){
    super(props)
    this.state = {
      input: '', 
      todos: []
    }
    this.handleChange = this.handleChange.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
    this.handleClick = this.handleClick.bind(this);
  }

  handleChange(event){
    this.setState({input: event.target.value})
  }

  handleSubmit(event){
    let arr = this.state.todos;
    let input = this.state.input;
    this.setState({todos: [...arr, input], input: ''})
    event.preventDefault();
  }

  handleClick(event,data){
    let todos = this.state.todos;
    let value = event.target.innerHTML;
    let idx = todos.indexOf(value);
    todos.splice(idx, 1)
    this.setState({todos: todos})
  }

  render(){
    return (
      <div>
        <h1>My todo List</h1>
        <form onSubmit={this.handleSubmit}>
          <input 
            type='text' 
            value={this.state.input} 
            onChange={this.handleChange} />
          <input type='submit' />
        </form>
        <ToDos onClick={this.handleClick} todos={this.state.todos} />
      </div>
    )
  }
}


ReactDOM.render(
  <Container />,
  document.getElementById('root')
);

2 个答案:

答案 0 :(得分:0)

您可以在父组件中创建 getKey 函数,并将其分配给子组件中的子道具。

通过这种方式,您可以在子组件中运行

this.props.getkey()

希望这会有所帮助。

答案 1 :(得分:0)

将内容传递给props.onClick

您已经在使用props.onClick将数据向上传递给父级,为什么不在那里也将index传递给父级。

const ToDos = (props) => {
  let todos = props.todos.map((value,index) => {
    return <li key={index} onClick={event => props.onClick(event, index)}>{value}</li>
  });
  return <ul>{todos}</ul>
};

这里的重要部分是 onClick={event => props.onClick(event, index)}