父组件向子组件传值
父组件通过属性进行传递,子组件通过props获取
//父组件 class CommentList extends Component{ render(){ return( <div> <Comment comment = {information} /> </div> ) } } //子组件 class Comment extends Component{ render(){ return( <div> <p>{this.props.comment}</p> </div> ) } }
父组件CommentList 引用子组件Comment时设置comment属性传递information,
再组件comment中通过this.props.comment获取到information的值
子组件向父组件传值
通过回调进行传递数据
//父组件 export default class Home extends Component { constructor(props){ super() this.state={ data:"请选择你喜欢的课程" } } aa=(item)=>{ this.setState({ data:item }) } render() { console.log(this.state.data) return ( <div> <div> <input type="text" placeholder={this.state.data} /></div> <Item a={this.aa} /> </div> ) } } //子组件 export default class Item extends Component { constructor(props){ super() this.state={ data:[], state:false } } render() { // console.log(this.props) return ( <div style={{display:this.state.state?"none":"block"}}> { this.state.data.map((val,index)=>{ return <div key={index} className="d1" onClick={()=>{ this.setState({ data:this.state.data, state:!this.state.state }) this.props.a(val.title) }}>{val.title}</div> }) } </div> ) } // 发送请求 componentDidMount(){ axios.get("http://localhost:3000/data.json").then((response)=>{ console.log(response.data.data) this.setState({ data:response.data.data }) }).catch((error)=>{ console.log(error) }) } } //json文件 data.json { "data": [ { "id": "0", "title": "Vue.js" }, { "id": "1", "title": "AngularJS" }, { "id": "2", "title": "JavaScript" }, { "id": "3", "title": "React.js" } ] }
兄弟组件之间的传值
通过相同的父组件进行传递数据
子组件A通过回调函数形式将数据传给父组件,接着父组件通过属性将数据传递给子组件B
通过发布/订阅进行传递
在子组件A中 commentDidMount函数中,发布事件,在子组件B中commentDidMount函数中对事件进行监听
使用context进行传递
使用redux对state进行统一管理