首页 > 解决方案 > 我如何将数据从这里传输到这里

问题描述

我想将我在一个组件中获得的道具转移到另一个组件。

function StarWar(props) {

    function handleClick(e) {
        e.preventDefault();
        console.log(props.other)
        return <div><Battle value={props.other}/></div>
    }

    if (props.value == 0) {
        return <div>
            <button className="btn btn-warning starwar"
                onClick={handleClick}>
                Start war
            </button>
        </div>
    }
    return <h1>Choose {props.value} more avangers</h1>
}

从这里我想将值传递给在 handleClick(e) 中尝试的 Battle 这也是我的 Battle 课程

export class Battle extends React.Component {
    constructor(props) {
        super(props);
        console.log(props.value);
    }

    render() {
        return (
            <div>
                <h1>Battle begins here</h1>
            </div>
        )
    }
}

它对我来说是正确的,但值不绑定

标签: reactjs

解决方案


Use JSX and ternary operator concept to display Battle component.,这是您问题的有效解决方案。

  function StarWar(props) {

        function handleClick(e) {
            e.preventDefault();
            console.log(props.other)
            return <div><Battle value={props.other}/></div>
        }

        if (props.other == 0) {
            return <div>
                <button className="btn btn-warning starwar"
                    onClick={handleClick}>
                    Start war
                </button>
            </div>
        }
        return (
          <React.Fragment>
          {props.other !== null ? (
            <div>
              <Battle value={props.other} />
            </div>
          ) : null}
          <h1>Choose {props.value} more avangers</h1>
        </React.Fragment>    
        )
    }
  
class Battle extends React.Component {
  state = {
    value: this.props.value
  };
  componentWillReceiveProps(nextProps) {
    if (this.props.value !== nextProps.value) {
      this.setState({ value: nextProps.value });
    }
  }
  render() {
    return (
      <div>
        <p>{this.state.value}</p>
        <h1>Battle begins here</h1>
      </div>
    );
  }
}
    ReactDOM.render(<StarWar other="20"/>, document.getElementById('root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id='root' />


推荐阅读