跨组件共享数据
我们的目的是将 数据、UI、逻辑 拆解到不同的模块中。下面的例子介绍了一种典型的做法,无状态组件展示UI,在触发交互的时候,通过父组件的回掉函数来触发数据修改,变更的数据又通过父子间的数据流,流转到另一个UI组件,从而实现兄弟组件的数据交流。
import React from 'react'
const Buttons = ({ onIncrement, onDecrement }) => {
return (
<div>
<button onClick={() => onIncrement()}>+</button>
<button onClick={() => onDecrement()}>-</button>
</div>
)
}
const Display = ({ count }) => (<h1>{count}</h1>);
class Counter extends React.Component {
constructor(props) {
super(props)
this.state = {
count: 0,
}
this.handleCountIncrement = this.handleCountIncrement.bind(this)
this.handleCountDecrement = this.handleCountDecrement.bind(this)
}
handleCountIncrement() {
this.setState({
count: this.state.count + 1,
})
}
handleCountDecrement() {
this.setState({
count: this.state.count - 1,
})
}
render() {
return (
<div>
<Display count={this.state.count} />
<Buttons
onIncrement={this.handleCountIncrement}
onDecrement={this.handleCountDecrement}
></Buttons>
</div>
)
}
}
export default Counter
高阶组件
import React from 'react'
const List = ({data: gists}) => {
return (
<ul>
{
gists.map(gist => {
return <li key={gist.id}>{gist.description}</li>
})
}
</ul>
);
}
const widthData = url => {
return Component => {
return class extends React.Component {
constructor(props) {
super(props)
this.state = {
data: [],
}
}
componentDidMount() {
fetch(url).then(response => response.json()).then(data => this.setState({ data }))
}
render() {
return (
<Component {...this.state} {...this.props} />
);
}
}
}
}
const withGists = widthData('https://api.github.com/users/gaearon/gists');
const ListWithGists = withGists(List);
const widthData = url => component => ()
const withGists = withData(‘http://xxx‘);
const ListWithGists = withGists(List);
export ListWithGists