javascript - 是否可以像 JavaScript 中的代码片段所示那样传递变量值?
问题描述
我想在单击按钮时生成随机颜色。请问这是生成随机颜色的正确方法吗?
randomColor = "#" + Math.floor(Math.random() * 16777215).toString(16);
// --- more code ---
changeHeaderColor() {
console.log("Change_header_color_was_clicked");
this.setState({ colors: "randomColor" });
}
// --- more code ---
render() {
return (
<h1 style={{ color: this.state.colors }}>
This is the header Component{" "}
<button onClick={() => this.changeHeaderColor()}>
Change Header Color
</button>
</h1>
);
}
解决方案
而不是这样做并将其设置为状态,因为您是以静态方式进行的,您所能做的就是简单地说:
const randomColor = '#'+Math.floor(Math.random()*16777215).toString(16);
然后使用:
<h1 style={{color: randomColor}}>
您可以通过更改强制重新渲染的状态变量来获得简单的重新渲染选项。
完整代码
import React, { useState } from "react";
export default function App() {
const [change, setChange] = useState(0);
const randomColor = "#" + Math.floor(Math.random() * 16777215).toString(16);
const style = { color: randomColor };
const handleChange = (e) => {
e.preventDefault();
// Just trigger a change.
setChange(change + 1);
};
return (
<div className="App">
<h1 style={style}>Hello CodeSandbox</h1>
<button onClick={handleChange}>Change Colour</button>
</div>
);
}
预览
推荐阅读
- openstack - 在同一计算节点中将 compute_driver 与 libvirt.LibvirtDriver 和 ironic.IronicDriver 一起使用
- c - 删除数组中的空内容并在 C 中对数组进行排序
- python - Python - datetime.now() 返回不正确的时间
- sql - 对两个表进行分组并对结果 VBA ADODB SQL 查询执行左连接
- java - 线性布局java和xml
- sql-server - 根据 UPDATE 结果有条件地使用 SQL OUTPUT 子句
- hadoop - 是否可以将弹性搜索查询转换为可以在 hadoop 上应用相同过滤逻辑的东西?
- java - Do-While 循环用户输入不循环
- reactjs - setState 多变量的三元
- haskell - IHaskell 和 Latex