foreword
The last tweet talked about the value-passing method of parent-child components in react. Today, I will talk about how grandchildren components perform value-passing operations. Let’s write a small case to explain the middle process.
grandchild component pass value
Let's write a case where the outermost component passes values to the grandchild components
outermost component
The outermost component (ancestral component) index.js:
1. Define a list array in the state, we need data to make a drop-down box here
2. Deconstruct the state in the render, first use list.map to loop out the Parent parent Component, and bind key, value and color to the parent component
3. Write a select drop-down box, the requirement is to change the value of the grandchild component through the selection value of the drop-down box of the outer component, bind the onChange time to the select, and write handleSelect function to change the value of color
export class Index extends Component {
state = {
list: [
{
id: 1, value: 'blue' },
{
id: 2, value: 'red' },
{
id: 3, value: 'green' }
],
color: 'red'
}
handleSelect = (e) => {
this.setState({
color: e.target.value})
}
render() {
let {
list, color } = this.state
return (
<div>Index Page
<select value={
color} onChange={
this.handleSelect}>
{
list.map(item => <option key={
item.id}>{
item.value}</option>)
}
</select>
{
list.map(item => <Parent key={
item.id} value={
item.value} color={
color} />)
}
</div>
)
}
}
parent component
1. Bind the value to the input input box, the value comes from the outer component
2. Also bind the onChange time to the input, and define its own name property in the state
3. Pass in {...this.props} to the Son component
import React, {
Component } from 'react'
import Son from './son'
export class Parent extends Component {
state = {
name: ''
}
handleChange = (e) => {
this.setState({
name: e.target.value})
}
render() {
return (
<div>Parent Page
<input type="text" value={
this.props.value} onChange={
this.handleChange} />
<Son {
...this.props} />
</div>
)
}
}
export default Parent
grandson component
Now you need to pass the value of the outermost component, you can change the color of the grandchild component.
Add the style binding color to the button directly as this.props.color, and the value in the button is {this.props.value}<
import React, {
Component } from 'react'
export class Son extends Component {
render() {
return <button style={
{
"color": this.props.color}}>{
this.props.value}</button>
}
}
export default Son
In this way, we successfully pass the outermost value to the grandson component inside~
To achieve the final effect:
At last
These two articles are about using props to pass values. The next lesson will introduce the method of passing values in context, which is also a very common method of passing values in react.
Pay attention and keep updating~