Open yaofly2012 opened 4 years ago
children
属性;
import React from 'react';
class Index extends React.Component { render() { console.log(this.props.children); return (
export default function() { return ( <Index children={["b", "c"]}> ) }
这种情况下children的数据类型完全由开发者明确指定的。
2. React隐式的添加`children`属性,包含在开始和结束标签之间的 JSX 表达式内容将作为特定属性 props.children 传递给外层组件;
```jsx
import React from 'react';
class Index extends React.Component {
render() {
console.log(this.props.children);
return (<div>{this.props.children}</div>)
}
}
export default function() {
return (
<Index>
Hello World
</Index>
)
}
这也是经常遇到的场景。
组件是React的核心。你可以像嵌套HTML标签一样嵌套使用这些组件,这使得编写JSX更加容易因为它类似于标记语言。
children
属性类型children
属性的取值;children
属性为数组,数组的每个元素就是嵌套在组件内的组件或者表达式;children
属性值直接是该嵌套元素的值(所以children属性不一定是数组);children
属性或者数组的元素(当children是数组时)本质上可以是任意类型的数据。但是并不是所有类型的数据都可以被正确渲染(看深入理解JSX)。
import React from 'react';
class Index extends React.Component { render() { console.log(this.props.children); return (
export default function() { return (
) }
> Objects are not valid as a React child (found: object with keys {a}). If you meant to render a collection of children, use an array instead.
## 操作`children`属性
>“children是一个不透明的数据结构”
虽然类型不定,但是属性的特性是固定的([Props are Read-Only](https://reactjs.org/docs/components-and-props.html)),无论是方式1还是方式2指定children属性值,React内部都会重新复制一份对应的值,但修改了特性值:
**children属性和属性值(数组时)都是只读的,可枚举的的,不可配置的:**
```javascript
{
configurable: false,
enumerable: true,
writable: false
}
import React from 'react';
class Index extends React.Component {
render() {
console.log(this.props.children);
return (<div>
{this.props.children.sort().join(',')} {/*为啥不能直接调用sort*/}
</div>)
}
}
export default function() {
return (
<Index>
{'bananas'}{'oranges'}{'apples'}
</Index>
)
}
TypeError: Cannot assign to read only property '1' of object '[object Array]'
children属性是数组了,为啥不能直接调用sort,而非得通过React.Children.toArray转换下
?
报错原因TypeError: "x" is read-only
props.children
数组是只读的,sort方法触发了对只读属性的写操作。
props
Props and Data Flow in ReactJS
一、
props
props
是组件的输入参数,是父组件向子组件传递数据的唯一途径。props
是只读的。1.1 访问
props
props
是只读的。从React 0.14开始会把props
对象进行冻结(Object.freeze
),但不会递归的去冻结props
的子属性。摘自React: Why are props not frozen?
为什么必须是只读的
React文档里这样说到:
组件具有
state
和props
,组件可以通过setState
管理state
,并且组件只能管理自己的state
。组件是不可以管理自己的props
,因为props
是组件的输入,一般来自父组件的state
,所以对子组件来说props
是只读的,不可以修改props
,如果要修改得由props
数据来源的父组件修改。为什么不递归的冻结
props
的子属性state
有关,state
的变化跟踪也只是针对state
的子属性。总结:
props
作为组件的输入,所有的React组件必须像纯函数那样使用它们的输入(即props
)1.2 指定默认值
约定静态属性
defaultProps
指定组件属性的默认值:undefined
时,则尝试从defaultProps
里取默认值;props
参数值应用默认值,更新阶段的componentWillReceiveProps
方法的参数也会被尝试应用默认值。defaultProps
只应用在属性的子属性上,不会递归处理。1.3 特殊的属性
有些属性是Reactjs内部处理的
明明写了,却没有收到
ref
key
明明没写,却收到了
children
传给
style
属性的对象React除了不建议
props
对象作为可修改对象外,还不建议把传给style
属性的对象作为可修改对象。并且从React 16开始也把传给style
属性的对象冻结了(Object.freeze
):参考