首页 > 解决方案 > 是否可以像 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>
  );
}

标签: javascriptreactjs

解决方案


而不是这样做并将其设置为状态,因为您是以静态方式进行的,您所能做的就是简单地说:

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>
  );
}

演示: https ://24jbd.csb.app/

预览

在此处输入图像描述


推荐阅读