补充:
思考打印结果
分析:
源码贴图
react这么操作应该是为了避免用户忘记传props,所以现在可传可不传。
子调用父函数通信:
-
函数传递
在父组件引用子组件的时候,之前传的都是单纯的单一属性:
父传子的时候
现在传递也是值,只不过后面是函数,不过要处理this指向问题
1.直接传箭头函数调用(推荐)
2.手动绑定this
3.定义时候用箭头函数
三种不同方式
子组件直接解构出对应的变量就是函数,方法触发时候使用即可
最后效果
//app.js
import React, { Component } from "react";
export default class App extends Component {
constructor() {
super();
this.state = {
counter:10
};
}
render() {
return (
<div>
<h2>App组件</h2>
<h3>{this.state.counter}</h3>
<hr />
{/* <Childtest name="方式一" age={18} addNum={e=>this.add()} /> */}
{/* <Childtest name="方式二" age={18} addNum={this.add.bind(this)} /> */}
<Childtest name="方式三" age={18} addNum={this.increament} />
<hr />
</div>
);
}
add(){
this.setState(
{
counter:this.state.counter+1,
}
)
}
increament=()=>{
this.setState(
{
counter:this.state.counter+1,
}
)
}
}
class Childtest extends Component {
render() {
const {addNum}=this.props;
return (
<div>
<h2>子组件</h2>
<button onClick={addNum}>+1</button>
</div>
);
}
}
案例:
效果预览- 里面用到父传子、子传父的相互传值
- 如果不变化的数据可以单独提出,不用全部放在state里面
- 单独设置的样式文件style.css需要在index.js入口文件引用一下
//app.js
import React, { Component } from "react";
export default class App extends Component {
constructor() {
super();
this.tabs=["流行", "新款", "精选"];//如果不变的东西一般放在这,不用全部放在state里面
this.state = {
counter: 10,
tabIndex:0
};
}
render() {
return (
<div>
<Childtest tabs={this.tabs} Index={(ChildValue)=>this.getIndex(ChildValue)} />
<div>
<h3>内容根据tab切换变化:</h3>
<p>{this.tabs[this.state.tabIndex]}</p>
</div>
</div>
);
}
getIndex(value){
this.setState({
tabIndex:value
})
}
}
class Childtest extends Component {
constructor(){
super()
this.state={
currentIndex:0
}
}
render() {
const { tabs,Index } = this.props;
return (
<div>
<div className="tabbar">
{tabs.map((item,index) => {
return (
<div key={item} className="tab-item">
<span
className={ this.state.currentIndex===index?"active":""}
onClick={e=>this.tabClick(index,Index)}>
{item}
</span>
</div>
);
})}
</div>
</div>
);
}
tabClick(index,fn){
console.log(index);//0,1,2
//同时把这个序号传给父组件,然后父组件根据index 显示对应的文字,fn在这解构也行,如果不传的话
fn(index);
this.setState({
currentIndex:index
})
}
}
//style.css
body{
margin: 0;
padding: 0;
}
.tabbar{
display: flex;
height: 44px;
line-height: 44px;
justify-content: space-around;
}
.tab-item{
flex: 1;
text-align: center;
}
.tab-item span{
padding: 5px 8px;
}
.tab-item span.active{
border-bottom: 2px solid red;
color: red;
}
网友评论