reactjs - 如何在组件之间传输数据 - 反应?
问题描述
我在反应中有 2 个组件按钮和 lvlchecker,button.js 看起来像这样:
import React from "react";
class Button extends React.Component {
state = {
clickCounter: 0
};
handleClick = () => {
this.setState(prevState => {
return { clickCounter: prevState.clickCounter + 1 };
});
};
render() {
return (
<div>
<button onClick={this.handleClick}>Click</button>
<p>CLICKS: {this.state.clickCounter}</p>
</div>
);
}
}
export default Button;
我想将数据从这个组件(clickCounter 函数)传输到其他组件。如何在其他组件中使用有关点击次数的信息?
解决方案
下面是一个示例,当它们作为兄弟姐妹相关时,如何Button
将一些数据发送到组件,例如Info
App
|
|
--------|--------
| |
| |
Button Info
代码:
class App extends React.Component {
state = {
// Now the state is duplicated because clickCounter lives both
// inside Button and App. You could just leave the clickCounter in
// App and remove it from Button. Then you would also pass the
// clickCounter to Button as props as you pass it to Info.
// This way state would not be duplicated and in general it is advised
// in React to not duplicate state.
clickCounter: 0
};
render() {
return (
<div>
<Button
clickHandler={cc => {
this.setState({ clickCounter: cc });
}}
/>
<Info counter={this.state.clickCounter} />
</div>
);
}
}
class Info extends React.Component {
render() {
return (
<div>
<p>Info: {this.props.counter}</p>
</div>
);
}
}
class Button extends React.Component {
state = {
clickCounter: 0
};
handleClick = () => {
this.props.clickHandler(this.state.clickCounter + 1);
this.setState(prevState => {
return { clickCounter: prevState.clickCounter + 1 };
});
};
render() {
return (
<div>
<button onClick={this.handleClick}>Click</button>
<p>CLICKS: {this.state.clickCounter}</p>
</div>
);
}
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
<div id="root"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
其他场景请参考这里。
推荐阅读
- javascript - 寻找没有增强现实的自然特征检测库
- java - 关于如何比较均匀地划分列表
- python - 为什么转换进入数据集而不是 Pytorch 中的 NN 本身?
- python - 在 ForeignKey 中创建或获取默认对象
- javascript - 想要在第一个语句完成执行后重定向反应
- vagrant - 初始化 Fabric CA 服务器时出错,go-sqlite3 需要 cgo 才能工作
- c# - 传递给 ViewDataDictionary 的模型项的类型是......但是这个 ViewDataDictionary 实例需要一个类型的模型项...... NET Core MVC
- python - python将多列一一添加到excel文件中
- r - 在R中的绘图中添加垂直线连接点到水平线
- python - 如何使用python创建一个一张一张地绘制散点图的视频?