javascript - 在 React 中使用自定义函数

标签 javascript reactjs

我有一个这样的组件

class Hourly extends Component {
  render() {
    return (
      <div key={this.props.key} id={this.props.id} className="col-xs-3 text-center vcenter box parent">
        <div className="child">
          <div>{this._theDay(this.props.day)}</div>
          <div>{this.props.summary}</div>
        </div>
      </div>
    );
  }
}

我想在组件中使用自定义函数 (_theDay),稍后我会在另一个组件中使用该函数

自定义函数:

_theDay(time) {
   moment.locale('en-gb');
   var dateTime = moment(time*1000).format('dddd');
   return dateTime;
  }

我稍后调用该组件

        <Hourly
          key={hour.time}
          id={hour.time}
          day={hour.time}
          summary={hour.summary}
        />

但是我收到错误:Uncaught (in promise) DOMException: Failed to execute 'removeChild' on 'Node': The node to be removed is not a child of this node.(…)

当我只使用<div>{this.props.day}</div>;时一切正常,但我无法使用我的自定义函数

最佳答案

我认为这与 React 在 props 更改后尝试更新 DOM 有关。尝试使用 <div/> 上的按键绑定(bind)到props.day帮助它知道 children 已经改变。

class Comp extends React.Component {
  render() {
    let day = this._theDay(this.props.day)
    return <div key={day}>{day}</div>;
  }
}

这是documentation on reconciling the DOM.

关于javascript - 在 React 中使用自定义函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40793494/

相关文章:

javascript - asp.net web api 405方法不允许,发布,自定义操作

javascript - 使用 Brave 浏览器的 Puppeteer?

javascript - 该网站在 ie 中使用脚本窗口错误

reactjs - TypeScript - React 上下文不适用于新的 PropTypes 包

android - 如何在 React Native 的抽屉导航中使用 ContextAPI?

javascript - react 计算器 : limiting number of inputs

javascript - 在我将 javascript 添加到导航组件后,HTML href 链接不起作用

javascript - MapBox GLJS - 使用 for 循环创建标记时不显示

reactjs - 如何将 Yup 验证架构与 `react-hook-form` lib 中的 Controller 组件一起使用

javascript - 使用 Jest 模拟 Firebase onValue 函数