一、解决了什么问题?

props是组件(包括函数组件和class组件)间的内置属性,用其可以传递数据给子节点。

二、怎么使用?
1、只读

props在传递数据的过程中,是只读的不能修改。

class App extends React.Component {
    // 第一步:给节点设置属性 `theme`
    render() {
        return <Toolbar theme="dark" />;
    }
}

function Toolbar(props) {
    // 第二步:子节点可以访问父节点的props属性,但只能读取不能修改
    return (
        <div>
            <ThemedButton theme={props.theme} />
        </div>
    );
}

class ThemedButton extends React.Component {
    // 第三步:孙子节点依然可访问props属性,同样只能读不能修改 
    render() {
        return <Button theme={this.props.theme} />;
    }
}
2、{...props}

展开props属性的一种简洁写法,属于 js展开语法

var props = { x: 1, y: 1, z:1 };
<Component {...props} />

// 上面等价于下面的写法
<Component x=1 y=1 z=1 />
3、props.children

指组件的子元素,下面 {props.children} 就是指 : "Hello world!"

<Welcome>Hello world!</Welcome>

function Welcome(props) {
    return <p>{props.children}</p>;
}

对于 class 组件,请使用 this.props.children 来获取:

class Welcome extends React.Component {
    render() {
        return <p>{this.props.children}</p>;
    }
}

三、参考链接:

Learn_anything
7 声望0 粉丝

收集互联网优质资源!


引用和评论

0 条评论