使用React将检查的值从子级返回到父级和祖父母级组件 [英] Return checked value from Child to Parent and to Grandparent component using React

查看:53
本文介绍了使用React将检查的值从子级返回到父级和祖父母级组件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在列出学生姓名及其ID的列表.每当呈现列表元素时,Parent类都会调用Child类.

I am making a list of names of students and their ID's. The Parent class calls upon Child class whenever a list element is to be rendered.

export default class Parent extends Component {    
  render() {
    return (
      <div>
        <div>
          <ul>{this.props.studentData.map(item => {
            return(
            <div><Child key={item.id} {...item} /></div>);
          })}
          </ul>
          <button>Submit</button>
        </div>
      </div>
    );
  }
}

export default class Child extends Component {
  render() {
    let {name}=this.props;
    return (
      <li><input type="checkbox"/>{name}</li>
    );
  }
}

我正在尝试在列表下方放置一个提交按钮,该按钮返回一个或多个已检查学生姓名的结果.我不明白的是,如何将学生名称的值从子级"组件返回到父级",并一直返回到层次结构的顶部并存储在某种变量中.有没有一种方法可以将值返回给父组件,即进行调用的组件?

I am trying to place a submit button under the list which returns the result of checked student name, one or many. What I don't understand is that how to return the value of student name from the Child component to Parent and all the way to the top of the hierarchy and store in some kind of variable. Is there a way to return values to the parent components i.e the components that make a call?

推荐答案

您可以将回调函数发送给 Child ,该回调函数在被选中或未选中时会进行通知.

You can send a callback function to Child which notifies whenever it has been checked or unchecked.

const Child = ({ id, name, onChange }) => 
  <li>
    <input
      type="checkbox"
      onChange={(event) => onChange(id, event.target.checked) }
    />
    {name}
  </li>

class Parent extends React.Component {
  constructor() {
    super()

    this.handleChange = this.handleChange.bind(this)
  }

  handleChange(id, checked) {
    console.log(`student ${id} is ${checked ? 'checked' : 'unchecked'}`)
  }

  render() {
    return (
      <div>
        <ul>
          {this.props.studentData.map(item =>
            <Child key={item.id} {...item} onChange={this.handleChange} />
          )}
        </ul>
      </div>
    )
  }
}

const studentData = [
  { id: 1, name: 'Student 1' },
  { id: 2, name: 'Student 2' },
  { id: 3, name: 'Student 3' },
]


ReactDOM.render(
  <Parent studentData={studentData} />,
  document.getElementById('root')
)

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>

这篇关于使用React将检查的值从子级返回到父级和祖父母级组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆