react学习笔记3--组件和属性

组件可以接收任意的输入(成为“props)并返回react元素

函数式组件和类组件,最简单的定义组件的方法是定义一个JavaScript函数

function welcome(props) {
    return <h1>hello,{props.name}</h1>;
}

这就是一个react组件,接收一个props参数,返回一个react元素

也可以用一个ES6的class来定义一个组件

class welcome extends React.Component{
    render() {
        return <h1>hello,{this.props.name}</h1>;
    }
}

渲染一个组件,元素也可以代表用户定义的组件:

const element = <welcome name="Sara" />;

当react遇到用户定义组件的元素时,将属性以一个单独对象的形式传递给相应的组件,成为props对象

function welcome(props) {
    return <h1>hello,{props.name}</h1>;
}
const element = <welcome name="Sara" />;
ReactDOM.render(
    element,
    document.getElementById('root')
);

合成组件

组件可以在他们的输出中引用其他组件:

function App() {
    return(
        <div>
            <welcome name="Sara" />
            <welcome name="Cahal" />
            <welcome name="Edite" />
        </div>
    );
}

ReactDOM.render(
    <App />,
    document.getElementById('root')
);

猜你喜欢

转载自blog.csdn.net/weixin_36926779/article/details/80975456
今日推荐