react-组件间的传值
2024-10-11 15:50:49
父组件向子组件传值
父组件通过属性进行传递,子组件通过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进行统一管理
最新文章
- .net多线程
- ARPSpoofing教程(四) - 捕获并分析数据包
- CodeForces - 405C
- 编写一个函数func(),将此函数的输入参数(int型)逆序输出显示,如54321 –>; 12345,要求使用递归,并且函数体代码不超过8行
- Window 2008 R2 + IIS7.5 + VS2013 错误代码 0x80070002
- 速卖通---发布商品aeopAeProductPropertys这个字段值报07004013的错误
- Java 编程的动态性,第 5 部分: 动态转换类--转载
- ZCTF-Pwn
- 基于visual Studio2013解决算法导论之049活动选择问题
- HDFS中PathFilter类
- Coursera 机器学习笔记(六)
- 【转】利用matlab生成随机数函数
- anguar-select2
- telnet操作memcache
- Atom插件安装及推荐
- MySQL针对对账数据,每天每个店只能产生一条对账记录,对数据库数据进行添加联合唯一索引设置
- 路由交换02-----ARP协议
- Tensorflow检验GPU是否安装成功 及 使用GPU训练注意事项
- day11hadoop高可用和Hive
- Tomcat学习总结(6)——Tomca常用配置详解