React 三大属性state,props,refs以及组件嵌套的应用
该项目实现了一个简单的表单输入添加列表的内容
代码如下
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>Hello React!</title>
<script src="https://cdn.staticfile.org/react/16.4.0/umd/react.development.js"></script>
<script src="https://cdn.staticfile.org/react-dom/16.4.0/umd/react-dom.development.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/prop-types/15.6.0/prop-types.js"></script>
<script src="https://cdn.staticfile.org/babel-standalone/6.26.0/babel.min.js"></script>
</head>
<body>
<div id="example"></div>
<script type="text/babel">
class App extends React.Component {
constructor(props) {
super(props)
this.state = {
tudo : ["吃饭", '睡觉', '玩耍']
}
//将自定义函数中的this绑定到父类里
this.AddData = this.AddData.bind(this);
}
AddData (data) {
//取出状态
const {tudo} = this.state;
tudo.unshift(data);
//更新状态
this.setState({tudo});
}
render() {
return (
<div>
<h2>小潘的行为</h2>
<Add tudo = {this.state.tudo} AddData={this.AddData}/>
<List tudo = {this.state.tudo}/>
</div>
)
}
}
class Add extends React.Component {
constructor(props) {
super(props)
//将自定义函数中的this绑定到父类里
this.add = this.add.bind(this);
}
add () {
const value = this.input.value;
if (!value) return ;
this.props.AddData(value);
this.input.value = '';
}
render() {
const {tudo} = this.props;
return (
<div>
<input type="text" ref = {input => this.input = input}/>
<button onClick = {this.add}>Add #{tudo.length + 1}</button>
</div>
)
}
}
Add.propTypes = {
tudo : PropTypes.array.isRequired,
AddData: PropTypes.func.isRequired
}
class List extends React.Component {
render() {
const {tudo} = this.props;
return (
<ul>
{
tudo.map( (tudo, index) => <li key={index}>{tudo}</li> )
}
</ul>
)
}
}
List.propTypes = {
tudo : PropTypes.array.isRequired
}
ReactDOM.render( <App /> , document.getElementById('example'));
</script>
</body>
</html>