我想将一个组件中的道具转移到另一个组件中。
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 这也是我的战斗课
export class Battle extends React.Component {
constructor(props) {
super(props);
console.log(props.value);
}
render() {
return (
<div>
<h1>Battle begins here</h1>
</div>
)
}
}
它对我的显示正确,但是值不绑定
答案 0 :(得分:2)
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' />