跨组件共享数据

    我们的目的是将 数据、UI、逻辑 拆解到不同的模块中。下面的例子介绍了一种典型的做法,无状态组件展示UI,在触发交互的时候,通过父组件的回掉函数来触发数据修改,变更的数据又通过父子间的数据流,流转到另一个UI组件,从而实现兄弟组件的数据交流。

    1. import React from 'react'
    2. const Buttons = ({ onIncrement, onDecrement }) => {
    3. return (
    4. <div>
    5. <button onClick={() => onIncrement()}>+</button>
    6. <button onClick={() => onDecrement()}>-</button>
    7. </div>
    8. )
    9. }
    10. const Display = ({ count }) => (<h1>{count}</h1>);
    11. class Counter extends React.Component {
    12. constructor(props) {
    13. super(props)
    14. this.state = {
    15. count: 0,
    16. }
    17. this.handleCountIncrement = this.handleCountIncrement.bind(this)
    18. this.handleCountDecrement = this.handleCountDecrement.bind(this)
    19. }
    20. handleCountIncrement() {
    21. this.setState({
    22. count: this.state.count + 1,
    23. })
    24. }
    25. handleCountDecrement() {
    26. this.setState({
    27. count: this.state.count - 1,
    28. })
    29. }
    30. render() {
    31. return (
    32. <div>
    33. <Display count={this.state.count} />
    34. <Buttons
    35. onIncrement={this.handleCountIncrement}
    36. onDecrement={this.handleCountDecrement}
    37. ></Buttons>
    38. </div>
    39. )
    40. }
    41. }
    42. export default Counter

    高阶组件

    1. import React from 'react'
    2. const List = ({data: gists}) => {
    3. return (
    4. <ul>
    5. {
    6. gists.map(gist => {
    7. return <li key={gist.id}>{gist.description}</li>
    8. })
    9. }
    10. </ul>
    11. );
    12. }
    13. const widthData = url => {
    14. return Component => {
    15. return class extends React.Component {
    16. constructor(props) {
    17. super(props)
    18. this.state = {
    19. data: [],
    20. }
    21. }
    22. componentDidMount() {
    23. fetch(url).then(response => response.json()).then(data => this.setState({ data }))
    24. }
    25. render() {
    26. return (
    27. <Component {...this.state} {...this.props} />
    28. );
    29. }
    30. }
    31. }
    32. }
    33. const withGists = widthData('https://api.github.com/users/gaearon/gists');
    34. const ListWithGists = withGists(List);

    const widthData = url => component => ()
    const withGists = withData(‘http://xxx‘);
    const ListWithGists = withGists(List);

    export ListWithGists