React(六)Props属性
发布时间:2020-12-15 20:22:48 所属栏目:百科 来源:网络整理
导读:state 和 props 主要的区别在于?props?是不可变的,而 state 可以根据与用户交互来改变。这就是为什么有些容器组件需要定义 state 来更新和修改数据。 而子组件只能通过 props 来传递数据。 (1)使用Props属性 class Mainextends React.Component { render(
state 和 props 主要的区别在于?props?是不可变的,而 state 可以根据与用户交互来改变。这就是为什么有些容器组件需要定义 state 来更新和修改数据。 而子组件只能通过 props 来传递数据。 (1)使用Props属性 class Mainextends React.Component { render() { return ( <div> <Name name={‘yulingjia‘} /> </div> ); } } class Name extends React.Component { render() { return ( <h1>{this.props.name}</h1> ); } } ? (2)默认Props class Mainextends React.Component { render() { return ( <h1>Hello,{this.props.name}</h1> ); } } Main.defaultProps = { name: ‘Yulingjia‘ }; ? (3)State 和 Props class Main React.Component { constructor() { super(); this.state = { name: "Yulingjia" } } render() { return ( <div> <Name name={this.state.name} /> </div> ); } } class Name extends React.Component { render() { return ( <h1>{this.props.name}</h1> ); } } ? (3)Props 验证 Props 验证使用?propTypes,它可以保证我们的应用组件被正确使用,React.PropTypes 提供很多验证器 (validator) 来验证传入数据是否有效。 var name= "Yulingjia"; class Name extends React.Component { render() { return ( <h1>Hello,{this.props.name}</h1> ); } } Name.propTypes = { name: PropTypes.string }; ReactDOM.render( <Name name={name} />,document.getElementById(‘example‘) ); (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |