props 操作小技巧

1, 抽象 props 抽象 props 一般用于跨层级传递 props,一般不需要具体指出 props 中某个属性,而是将 props 直接传入或者抽离道子组件中。

2,混入 props

function Son(props) {
console.log(props)
return <div>hello,wowld</div>
}

function Father(props) {
const fatherProps = {
mes: 'let us learn React',
}
return <Son {...props} {...fatherProps} />
}

function Index() {
const indexProps = {
name: 'alien',
age: '28',
}

return <Father {...indexProps} />
}

结果:

React之使用Props的小技巧_前端

Father组件一方面直接将Index组件的IndexProps抽象传递给了Son组件,一方面也混入了自己的fatherProps

3,抽离Props

有时候如果要从父组件Props中抽离某个属性,再传递给子组件。

function Son(props) {
console.log(props)
return <div>hello,world</div>
}

function Father(props){
const {age,...fatherProps} = props
return <Son {...fatherProps}></Son>
}

function Index () {
const indexProps = {
name: 'zhaomin',
age: '29',
mes: 'let us learn React!'
}

return <Father {...indexProps}></Father>
}

打印结果

React之使用Props的小技巧_javascript_02

4,注入props

a. 显式注入props(指的就是能够直观看见标签中绑定的props)

function Son(props){
console.log(props) // name: zhaomin age: 28
return <div>hello,world</div>
}

function Father (props) {
return props.children
}

function Index () {
return <Father>
<Son name="zhaomin" age="28"></Son>
</Father>
}

b.隐式注入 props (指的是通过React.cloneElement 对props.children 克隆再混入新的props)

function Son (props) {
console.log(props) // name: zhaomin age: 28 mes: 这是测试de
return <div>hello,world</div>
}

function Father (props) {
return React.cloneElement(props.children,{mes: '这是测试de'})
}

function Index () {
return <Father>
<Son name="zhaomin" age="28"></Son>
</Father>
}

关于props.children的操作

React之使用Props的小技巧_前端_03

 

打印效果

React之使用Props的小技巧_react.js_04

上述代码中,Container 为父级组件,Children为子级组件,父级组件嵌套子级组件的时候,在父级组件中可以通过props.children获取到父组件下的子级组件的元素。

代码为:

props.children.map || props.children.forEach

在获取到子元素后通过React.cloneElement 将数据混入props中。