【问题标题】:Fetch random color from api in react.js?从 react.js 中的 api 获取随机颜色?
【发布时间】:2020-02-29 20:05:51
【问题描述】:

如何从这个 API 链接 http://www.colr.org/json/color/random 获取随机颜色以及如何使用获取的颜色分别更改列表中的每个元素,例如为 react.js 中的一行列表添加每种颜色?

class FetchRandomColor extends React.Component {
state = {
    loading: true,
    color: null,
};

async componentDidMount() {
    const url = "http://www.colr.org/json/color/random";
    const response = await fetch(url);
    const data = await response.json();
    this.setState({color: data.colors[0]})
}


render() {
return (
    <div>
        {this.state.loading || !this.state.color ? (
        <div>loading...</div> 
        ) : (
        <div>
           div>{this.state.color}</div>
        </div>
        )}
    </div>
);

} }

渲染(, document.getElementById('root'));

到目前为止,我尝试了这个,但找不到从 api 获取颜色的方法,之后我需要将该颜色应用于列表的每一行

【问题讨论】:

  • 到目前为止你有什么尝试?
  • 你想做什么?贴一些代码

标签: javascript reactjs api get fetch


【解决方案1】:

我认为你可以使用 Math.random() 和 RGBa,这是一个例子https://www.freecodecamp.org/forum/t/react-random-color-change/227595

【讨论】:

    猜你喜欢
    • 2015-05-25
    • 2012-02-23
    • 2016-01-11
    • 1970-01-01
    • 1970-01-01
    • 2017-09-02
    • 2018-11-29
    • 2014-11-17
    • 1970-01-01
    相关资源
    最近更新 更多