前端那些事之react篇--子父组件传递
发布时间:2020-12-15 07:30:22 所属栏目:百科 来源:网络整理
导读:react的子父组件传递参数 父组件在state的状态下设置 getInitialState(){ return{ childNameA:"小样,你好吗?",childNameB:'小样,我不好!!',item:[ ],time:0 } 子组件用props属性来接收 p 子组件{this.props.name}/p 完成的代码:父组件代码 import Reac
react的子父组件传递参数父组件在state的状态下设置getInitialState(){ return{ childNameA:"小样,你好吗?",childNameB:'小样,我不好!!',item:[ ],time:0 } 子组件用props属性来接收<p >子组件{this.props.name}</p> 完成的代码:父组件代码import React from 'react'; import ReactDOM from 'react-dom'; import './commopent/childa/index'; import './index.css'; var ChildA=require('./commopent/childa/index'),ChildB=require('./commopent/childb/index') var App=React.createClass({ getInitialState(){ return{ childNameA:"小样,你好吗?",time:0 } },render(){ return( <div> <h3 className='app'>组件化开发</h3> <button onClick={this.plus}>{this.state.time}</button> <ChildA name={this.state.childNameA} plus={this.plus} time={this.state.time}/> <ChildB name={this.state.childNameB} items={this.state.item}/> </div> ) },plus:function () { var plaus=this.state.time; plaus++; var items=this.state.item; items.push('user click') this.setState({ time:plaus,item:items }) } }) ReactDOM.render( <App />,document.getElementById('root') ); 子组件A的代码import React from 'react'; import './child1.css' var ChildA=React.createClass({ getInitialState(){ return{ name:'小样' } },render(){ return( <div className='child'> <p >子组件{this.props.name}</p> <input type="text" value={this.state.name} onChange={this.change}/> {this.state.name} <button id="btn">原生事件</button> {/*<button onClick={this.hanldClick}>{this.state.times}</button>*/} <button onClick={this.props.plus}>{this.props.time}</button> </div> ) },change:function (e) { this.setState({ name:e.target.value }) },// hanldClick:function () { // var times=this.state.times; // times++; // this.setState({ // times:times // }) // },componentDidMount:function () { // var btn= document.querySelector("#btn"); // btn.onclick=function () { // alert("原生事件!!") // } } }) module.exports=ChildA; 子组件B的代码import React from 'react'; import './child.css' var ChildB=React.createClass({ render(){ var value=this.props.items.map(function (o,i) { return( <li>{o}+{i}</li> ) }) return( <div className='child'> <p>子组件{this.props.name}</p> <ul> {value} </ul> </div> ) } }) module.exports=ChildB 实现效果如下:(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |