javascript - 如何在 React 中记录道具?
问题描述
React 新手,这只是我上课的第一天。我要做的就是当我单击一个框时记录颜色道具。
我知道我不能做 console.log(this.props.color) 因为这是引用应用程序......现在这一切都很混乱......任何提示将不胜感激。
class Boxes extends Component{
render(props){
return (
<div className="boxes" onClick={this.props.getBoxColor}>
<div className="box1" color="red"></div>
<div className="box2" color="orange"></div>
<div className="box3" color="yellow"></div>
<div className="box4" color="green"></div>
<div className="box5" color="blue"></div>
</div>
);
}
}
class App extends Component {
getBoxColor=()=>{
console.log(this.props)
}
render() {
return (
<Boxes classColor={this.color} getBoxColor={this.getBoxColor} />
)
}
}
ReactDOM.render(<App />, document.getElementById('root'));
解决方案
试试这个,告诉我它是否适合你。
class Box extends React.Component {
render() {
const className = this.props.className;
const color = this.props.color;
return (
<div
className={className}
color={color}
onClick={() => console.log(color)}
/>
);
}
}
class App extends React.Component {
render() {
return (
<div>
<Box className="box1" color="red" />
<Box className="box2" color="blue" />
<Box className="box3" color="green" />
</div>
);
}
}
ReactDOM.render(<App />, document.getElementById("root"));
推荐阅读
- generics - 使通用属性延迟初始化(实例化)
- vba - VBA 中的 ODBC 刷新连接字符串错误/运行时错误 1004
- nginx - 在 yaml 中使用 pod 环境变量
- r - 基于R中条件的二分变量
- react-native - 在 Expo 零食模拟器中,我无法解决错误:无法重新定义属性:ThemeProvider
- c# - 使用三元运算符时,IEnumerable 未填充预期数据
- python-3.x - 即使安装在 google colab 中,也将目录更改为 google 驱动器时出错
- python - 在 TD Ameritrade API 上创建触发止损单的问题
- android - 单元测试:Android Rx java
- r - 如何在 R 上从 Internet 下载文件?