React属性的3种设置方式

一、

React属性的3种设置方式

不推荐用setProps,因为以React的设计思想相悖,推荐以父组件向子组件传递属性的方式

二、3种用法的代码

1.键值对

 <!DOCTYPE html>
<html lang="zh-cn">
<head>
<meta charset="UTF-8">
<title>Hello, World</title>
</head>
<body>
<script src="./react-0.13.2/react-0.13.2/build/react.js"></script>
<script src="./react-0.13.2/react-0.13.2/build/JSXTransformer.js"></script>
<script type="text/jsx">
var style = {
color: "red",
border: "1px #000 solid",
};
var HelloWorld = React.createClass({
render: function () {
return <p>Hello, {this.props.name ? this.props.name : "World"}</p>;
},
});
var HelloUniverse = React.createClass({
getInitialState: function () {
return {name: ''};
},
handleChange: function (event) {
this.setState({name: event.target.value});
},
render: function () {
return <div>
<HelloWorld name={this.state.name}></HelloWorld>
<br/>
<input type="text" onChange={this.handleChange} />
</div>
},
});
React.render(<div style={style}><HelloUniverse></HelloUniverse></div>, document.body);
</script>
</body>
</html>

2.{...props}展开属性

 <!DOCTYPE html>
<html lang="zh-cn">
<head>
<meta charset="UTF-8">
<title>Hello, World</title>
</head>
<body>
<script src="./react-0.13.2/react-0.13.2/build/react.js"></script>
<script src="./react-0.13.2/react-0.13.2/build/JSXTransformer.js"></script>
<script type="text/jsx">
var style = {
color: "red",
border: "1px #000 solid",
};
var HelloWorld = React.createClass({
render: function () {
return <p>Hello, {this.props.name1 + ' ' + this.props.name2}</p>;
},
});
var HelloUniverse = React.createClass({
getInitialState: function () {
return {
name1: 'Tim',
name2: 'John',
};
},
handleChange: function (event) {
this.setState({name: event.target.value});
},
render: function () {
return <div>
<HelloWorld {...this.state}></HelloWorld>
<br/>
<input type="text" onChange={this.handleChange} />
</div>
},
});
React.render(<div style={style}><HelloUniverse></HelloUniverse></div>, document.body);
</script>
</body>
</html>

3.setProps方法

 <!DOCTYPE html>
<html lang="zh-cn">
<head>
<meta charset="UTF-8">
<title>Hello, World</title>
</head>
<body>
<script src="./react-0.13.2/react-0.13.2/build/react.js"></script>
<script src="./react-0.13.2/react-0.13.2/build/JSXTransformer.js"></script>
<script type="text/jsx">
var style = {
color: "red",
border: "1px #000 solid",
};
var HelloWorld = React.createClass({
render: function () {
return <p>Hello, {this.props.name ? this.props.name : "World"}</p>;
},
});
var instance = React.render(<HelloWorld></HelloWorld>, document.body);
instance.setProps({name: 'Tim'});
</script>
</body>
</html>
上一篇:2013年江西理工大学C语言程序设计竞赛(高级组)


下一篇:js中数字调用方法后被包装成对象,typeof换成instanceof解决问题