【问题标题】:Trying to use componentWillReceiveProps to change the button color尝试使用 componentWillReceiveProps 更改按钮颜色
【发布时间】:2019-12-29 18:15:36
【问题描述】:
  • 我正在尝试使用 componentwillReceiveProps 来更改按钮颜色。
  • 当我点击新闻频道时,获取头条新闻按钮应该会改变颜色。
  • 所以我想在 Button.js 中我会使用 componentwillReceiveProps
  • 这样在收到道具后我会更改按钮颜色。
  • 但在 Button.js 的 componentwillReceiveProps 内没有打印任何内容。
  • 我研究并找到了以下链接,但仍然没有帮助我 How do i use componentWillReceiveProps() correctly?
  • 您能告诉我如何解决吗?
  • 在下面提供我的代码 sn-p 和沙箱

https://codesandbox.io/s/boring-wu-btlre

    class Button extends Component {
      componentWillReceiveProps(nextprops) {
        console.log("componentWillReceiveProps nextprops--->", nextprops);
      }
      render() {
        return (
          <div>
            <button
              onClick={() => {
                // getPosts(channel);
                //  getAlert();
              }}
              className="btn btn-primary btn-lg btn-block"
            >
              Get top news
            </button>
          </div>
        );
      }
    }

【问题讨论】:

  • Button 的父级长什么样子?
  • 没有打印,因为您没有在 Button 组件中传递任何道具
  • @Rikin 在我的代码 snadbox 中,你能像如何使用 componentWillReceiveProps 一样更新它吗...它太令人困惑了:(
  • 只需将任何道具传递给您的按钮,您应该会很好。如果你不知道该怎么做,我建议你退后一步,学习 React 基础知识,以免以后头疼。对于您所追求的可能值得的方法已弃用
  • 嘿,我尝试在 App.js 中添加道具,但仍然无法正常工作:(codeandbox.io/s/hopeful-villani-xyikq 你能在我的小提琴中更新吗,我坚持下去了

标签: javascript html css reactjs redux


【解决方案1】:

这是您来自 SandBOXapp.js,它清楚地表明您没有向按钮组件传递任何内容。这就是它没有显示任何内容的原因。

import React from "react";
import ChannelsField from "./ChannelsField";
import RecentChannelItem from "./RecentChannelValues";

import Button from "../containers/Button";
import TopNews from "../containers/TopNews";
const App = () => (
  <div>
    <RecentChannelItem />
    <ChannelsField />
    <Button />
    <TopNews />
  </div>
);
export default App;

【讨论】:

  • 在我的代码 snadbox 中,你能像如何使用 componentWillReceiveProps 一样更新它吗......它太令人困惑了:(
  • @tkkk here。使用你已经在做的第三种方法 Redux 你只需要简单地从 store 中获取数据。
  • @tkkk 因为您需要在单击频道时更新商店,并且每次在商店中更新时都会获得价值,例如this
  • 嘿看了你的两个链接,我正在尝试使用 componentwillreceiveprops 来实现它你能告诉我如何使用 componentwillreceiveprops 来实现它......如果你在我的代码沙箱中会很棒,它太令人困惑了:(
  • 嘿,我尝试在 App.js 中添加道具,但仍然无法正常工作 :( codesandbox.io/s/hopeful-villani-xyikq 你能在我的小提琴中更新吗,我坚持下去了
猜你喜欢
  • 2013-07-31
  • 1970-01-01
  • 1970-01-01
  • 2019-05-06
  • 2020-08-03
  • 2014-07-11
相关资源
最近更新 更多