reactjs - 我如何将数据从这里传输到这里
问题描述
我想将我在一个组件中获得的道具转移到另一个组件。
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>
)
}
}
它对我来说是正确的,但值不绑定
解决方案
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' />
推荐阅读
- php - Directus 计算字段/列
- python - 为什么在我的代码中 numba 比纯 python 慢?
- validation - 我必须将自定义对象客户的验证规则编写为
- reactjs - 根据路由改变导航 React 路由器
- javascript - 如何遍历以下充满图像的目录并将图像添加到我的 HTML 页面
- prolog - 如何在一系列数字上测试谓词并返回通过 Prolog 的那些
- python - 删除默认帮助命令
- r - 如何从多个回归模型中提取置信区间?
- html - 从 Wordpress 的主菜单中删除项目符号
- javascript - 什么时候虚拟 DOM 比真实 DOM 快?