父传子
父组件传值给子组件 给子组件标签绑定属性 在子组件内部直接使用props访问绑定数据。
state = {
selected: "",
};
render() {
const arr = ["北京", "上海", "深圳"];
const { selected } = this.state;
return (
<div className="wrap">
{arr.map((item, index) => (
<button key={index} onClick={() => this.setState({ selected: item })}>
{item}
</button>
))}
<Box
title="hello wrold"
className="test"
style={{ color: "#0ac" }}
value={selected}
></Box>
</div>
);
}
constructor(props){
super(props);
console.log(props);
}
render() {
return (
<div className={"box " + this.props.className} style={this.props.style}>
<h1>{this.props.value}</h1>
</div>
)
}
componentDidMount(){
console.log(this.props);
}
子传父
子组件传值给父组件:先在父组件调用子组件时绑定自定义属性,属性的值为回调函数。当子组件需要传值给父组件时,调用该属性对应的函数。
render() {
return (
<div className="wrap">
<Box
onChange={(item) => {
console.log(123, item);
}}
></Box>
</div>
);
}
render() {
const arr = ["北京", "上海", "深圳"];
return (
<div className="box">
{arr.map((item, index) => (
<button
key={index}
onClick={() => {
this.props.onChange(item);
}}
>
{item}
</button>
))}
</div>
);
}
componentDidMount() {
console.log(this.props);
}
兄弟传值
基于发布订阅者模式
1 eventBus
引入vue 不推荐 vue包很大 还不如插件划算
export default new window.Vue();
import eventBus from './eventBus/index.js'
render() {
return (
<div className="box">
<h1>one组件</h1>
{"abcd".split("").map((item) => (
<button key={item} onClick={this.btnAction(item)}>
{item}
</button>
))}
</div>
);
}
btnAction = (item) => () => {
eventBus.$emit("send", item);
};
componentDidMount() {
eventBus.$on("send", (value) => {
this.setState({ oneValue: value });
});
}
2 pubsub-js
import PubSub from 'pubsub-js'
render() {
return (
<div className="box">
<h1>one组件</h1>
{"abcd".split("").map((item) => (
<button key={item} onClick={this.btnAction(item)}>
{item}
</button>
))}
</div>
);
}
btnAction = (item) => () => {
PubSub.publish('send', item);
};
state = {
oneValue: "",
};
render() {
return (
<div className="box">
<h1>two组件</h1>
<p>value: {this.state.oneValue}</p>
</div>
);
}
componentDidMount() {
this.token = PubSub.subscribe('send', (message, data)=>{
this.setState({oneValue: data});
})
}
componentWillUnmount(){
PubSub.unsubscribe(this.token);
}
mitt
import mitt from "mitt";
const emitter = mitt();
export default emitter;
import emiter from './emiter/index.js'
render() {
return (
<div className="box">
<h1>one组件</h1>
{"abcd".split("").map((item) => (
<button key={item} onClick={this.btnAction(item)}>
{item}
</button>
))}
</div>
);
}
btnAction = (item) => () => {
emitter.emit('send', item);
};
state = {
oneValue: "",
};
render() {
return (
<div className="box">
<h1>two组件</h1>
<p>value: {this.state.oneValue}</p>
</div>
);
}
componentDidMount() {
emitter.on('send', this.onSend);
}
onSend = (value)=>{
this.setState({oneValue: value});
};
componentWillUnmount(){
emitter.off('send', this.onSend);
}
还有很多基于发布订阅者模式的插件 值得一试
|