2、Reactjs中的属性(this.props)
2016-01-17 14:56
393 查看
一、什么是属性
React官方文档上对于属性的介绍如下:React 里有一个非常常用的模式就是对组件做一层抽象。组件对外公开一个简单的属性(Props)来实现功能,但内部细节可能有非常复杂的实现。
React中的每一个组件,都包含有一个属性(props),属性主要是从父组件传递给子组件的,在组件内部,我们可以通过this.props获取属性对象
二、属性的使用方法
react中主要有下面三种方法来传递属性:1、直接在组件中使用key/value的形式来指定属性
下面的代码演示了如何使用key/value的形式指定属性:React.render( <HelloWorld name="Jack"/>, document.getElementById('container') );可以看到,在自定义的HelloWorld组件中,我们指定了一个name为Jack的属性,在组件中,获取属性的方法如下代码:
var HelloWorld = React.createClass({ render: function() { return ( <div>Hello, {this.props.name}</div> ); } });在{}中,通过this.props.name,就可以获取到我们指定的name属性的值了。
2、使用延展属性为组件指定属性
如下代码所示:<script type="text/jsx"> var HelloWorld = React.createClass({ render: function() { return ( <div>Hello, {this.props.name1}, {this.props.name2}</div> ); } }); var props = { name1: 'Jack', name2: 'Tom' }; React.render( <HelloWorld {...props}/>, document.getElementById('container') ); </script>为了在HelloWorld组件中定义多个属性,我们首先定义了一个props对象,里面包含两个键值对,然后在<HelloWorld>标签中,用{...props}的方式为组件传递了这两个属性,这就是JSX中的延展属性,"..."成为延展操作符,这种方式可以很方便地为组件指定多个属性,就相当于下面的代码:
React.render( <HelloWorld name1="Jack" name2="Tom"/>, document.getElementById('container') );
3、通过调用组件的setProps函数为组件指定属性
React.render()函数执行后,会返回代表组件的一个对象,通过调用这个对象的setProps函数,可以为其指定属性,如下代码:<script type="text/jsx">react官方认为,props应该是只读的,不应该被修改。因为 React 不能帮你检查属性类型(propTypes)。这样即使你的 属性类型有错误也不能得到清晰的错误提示。
var HelloWorld = React.createClass({ render: function() { return ( <div>Hello, {this.props.name}</div> ); } });
var instance = React.render(
<HelloWorld />,
document.getElementById('container')
);
instance.setProps({name: 'Jack'});
</script>
Props 应该被当作禁止修改的。修改 props 对象可能会导致预料之外的结果,所以最好不要去修改 props 对象。
相关文章推荐
- 微信公共号弹幕开发日志
- 从零开始构建前端和reactjs - 0
- Hello world React
- ReactJs 组件间数据传递
- Reactjs 之 mixins
- ReactJs 组件间通信
- reactjs 事件的用法
- Thinking In Relay #Facebook Relay文档翻译#
- Relay文档翻译目录 #Facebook Relay文档翻译#
- Mutations #Facebook Relay文档翻译#
- Connection #Facebook Relay文档翻译#
- Object Identification #Facebook Relay文档翻译#
- GraphQL Relay Specification #Facebook Relay文档翻译#
- Babel Relay Plugin #Facebook Relay文档翻译#
- Network Layer #Facebook Relay文档翻译#
- Mutations #Facebook Relay文档翻译#
- Ready State #Facebook Relay文档翻译#
- Root Container #Facebook Relay文档翻译#
- Routes #Facebook Relay文档翻译#
- Tutorial #Facebook Relay文档翻译#