【问题标题】:Re render functional component on props change在 props 更改时重新渲染功能组件
【发布时间】:2024-12-17 04:15:01
【问题描述】:

我无法在功能组件中呈现更新的道具。但是,我能够完美地控制台记录这些道具。

我的代码:

class ABC extends someOtherClass {
 static create(value) {
    let node = super.create();
    node.setAttribute('style', 'font-size:100%; color: white');
    node.setAttribute('id', Date.now());
    node.onclick = function(e) {
      HandleComments({ id: e.target.id, render: e.target.id });
    };
    return node;
  }
}

HandleComments 组件

import React from 'react';

const HandleComments = props => {
  console.log('props', props);
  return <div>{props.id}</div>;
};

export default HandleComments;

【问题讨论】:

  • 添加相关代码
  • 请添加代码。
  • 是的,您可能遗漏了一些东西。虽然没有看到您的代码,但我们不知道是什么。
  • @Avanthika 就是这么做的。你能看一下吗?
  • 你的 react 组件安装在哪里?看起来你只是在调用一个恰好返回 JSX 的函数

标签: javascript reactjs


【解决方案1】:

您在功能组件中使用this.props.id 而不是props.id

const HandleComments = props => {
  console.log('props', props);
  return <div>{props.id}</div>;
};

您还需要渲染 HandleComments 组件,而不是像下面这样将功能实例返回给 onClick 事件或从 someOtherClass 以其他方式返回

class ABC extends someOtherClass {
 static create(value) {
    let node = super.create();
    node.setAttribute('style', 'font-size:100%; color: white');
    node.setAttribute('id', Date.now());
    node.onclick = function(e) {
      ReactDOM.render(<HandleComments id={e.target.id} />, document.getElementById('root'));
    };
    return node;
  }
}

【讨论】:

  • 仍然无法渲染道具。
  • @Avanthika OP 没有渲染功能组件,而只是调用它,因此渲染没有发生
  • @Avanthika 在 console.log 上,我可以看到我的道具。
  • @ShubhamKhatri ReactDOM.render 不起作用,因为它不是 React 类,而只是一个普通类。
  • 在这种情况下最好不要遵循上述模式,而简单地使用 JSX 来渲染元素