Return checked value from Child to Parent and to G

2019-08-25 01:09发布

问题:

This question already has an answer here:

  • How to pass data from child component to its parent in ReactJS? 5 answers

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?

回答1:

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>