react组件传值传方法
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> <script src="../node_modules/react/umd/react.development.js"></script> <script src="../node_modules/react-dom/umd/react-dom.development.js"></script> <script src="../node_modules/babel-standalone/babel.js"></script> </head> <body> <div id="app"></div> <script type="text/babel"> class Txt extends React.Component{ constructor(props){ super(props); this.Input = this.Input.bind(this); } Input(e){ if(e.keyCode===13){ this.props.addItem(e.target.value); // e.target.value = ''; // this.refs.wbk.value = ''; this.jd.value = ''; } } render(){ console.log(this) // 官方推荐 将文本框的值挂载到函数实例上储存起来 很react的做法 return ( // <input type='text' onKeyUp={this.Input} ref='wbk'/> <input type='text' onKeyUp={this.Input} ref={(wb)=>this.jd=wb}/> ) } } class List extends React.Component{ constructor(props){ super(props); }; render(){ let {data:list} = this.props; return( // 这里绑定的this没有作用,只是为了返回一个没有立即执行的方法 <ul> { list.map((item,index)=>{ return <li key={index} style={{background:index===1?'red':'skyblue'}}> {item} <button onClick={this.props.remove.bind(this,index)}>del</button> </li> }) } </ul> ) } } class App extends React.Component{ // 进行props的继承 constructor(props){ super(props); // super继承根数据 this.state = { list:['aa','bb'] } // 绑定了这些方法调用的this this.addItem = this.addItem.bind(this); this.del = this.del.bind(this); }; addItem(str){ // 解构赋值 进行修改state状态 let list1 = [...this.state.list,str]; this.setState({ list:list1 }) }; del(idx){ let list1 = [...this.state.list]; list1.splice(idx,1); this.setState({ list:list1 }) } render(){ // 结构数据 let {list} = this.state; return ( // 进行传值和传方法 <div> <Txt addItem={this.addItem}/> <List data={list} remove={this.del}/> </div> ) } } ReactDOM.render( <App/>, document.getElementById('app') ) </script> </body> </html>