【问题标题】:How to get or update the value in variables in reactjs like angular?如何获取或更新 reactjs 中的变量值,如 angular?
【发布时间】:2021-11-20 04:42:59
【问题描述】:

下面有什么选择吗?

将类切换到 reactjs 中的特定元素

这是函数

variable: any

onclick() {
  this.variable = 'new value';
}

<img src={ham} className="cursor-pointer" width="40" alt="" onClick={this.handleClick} />
<div className={this.variable + ' cursor-pointer'}>
  Content
</div>

【问题讨论】:

    标签: reactjs typescript tsx react-tsx


    【解决方案1】:

    如果您想切换传递给元素的className,则存储布尔状态并有条件地添加类名。在点击处理程序中切换状态值。

    type MyState = {
      variable: boolean;
    };
    
    class Header extends Component<any, MyState> {
    
      state: MyState = {
        variable: false
      }
    
      handleClick = () => {
        this.setState(prevState => ({ variable: !prevState.variable }));
      }
    
      ...
    
      <img
        src={ham}
        className="cursor-pointer"
        width="40"
        alt=""
        onClick={this.handleClick}
      />
      <div className={this.state.variable ? 'cursor-pointer' : ''}>
        Content
      </div>
    

    【讨论】:

    • 嗨,Drew,感谢您的快速回复,但收到此错误“Readonly”类型上不存在属性“变量”。 TS2339
    • @PonsakthiAnand 我并不精通 Typescript,但我知道这只是意味着你需要为你的组件状态定义接口/类型,无论你使用什么状态变量。我没有在我的回答中使用 Typescript,IMO 与切换状态和设置类名的问题无关。不过,我会更新我的答案以包含一个示例。
    • ibb.co/rbFLx38 这是我使用的代码。请检查您是否可以提供帮助
    • @PonsakthiAnand 太棒了,欢迎您。不要忘记对您在 stackoverflow 上找到的有用和/或有用的问题、答案和 cmets 进行投票。干杯,祝你好运。
    猜你喜欢
    • 2022-12-10
    • 2022-01-06
    • 2021-11-26
    • 1970-01-01
    • 2018-10-24
    • 1970-01-01
    • 2021-01-03
    • 2021-04-25
    • 2020-11-10
    相关资源
    最近更新 更多