2017-04-18 38 views
1

如何在组件更新后删除类?例如,反应:删除componentWillUpdate后的类样式

//fire update where fieldname is array of changed fields 
componentWillUpdate(){ 
    $(`.input-${fieldName}`).addClass('highlight'); 
} 

我想火此功能的事件处理程序被点击

removeFields (fieldName) { 
    //remove highlight updated field name when it is updated 
    $(`.input-${fieldName}`).removeClass('highlight'); 
} 
+0

只需添加''或者类似的东西。如果你不需要问题,你应该从你的项目中删除jQuery。 – elmeister

+0

如果有超过100个我需要更改的字段,那将不可能。我正试图做动态的。 – Demon

回答

2

一前一后不应该利用jQuery来更新使用React呈现的DOM元素。

为什么:原因是React呈现组件当state/props变化。这种重新渲染会覆盖jQuery所做的更改,并且会让您无可奈何。

解决方案:为每个需要采取的逻辑操作保持一个状态。

对于您的情况,您需要维护一个booleanstate变量以指示组件是否已更新。最初,如果你的构造函数是错误的(类似于下面)。

constructor() { 
this.state = { 
    isUpdated: false 
} 
} 

当你的逻辑命中,使用this.setState({isUpdated: true})更新此状态变量设置为true,当事件处理程序使其为false使用this.setState({isUpdated: false})所以当事件发生时,这将是错误的。

在渲染方法,利用这个变量来确定类名已被添加到DOM元素或如果使用太多的逻辑来处理 classNames那么不喜欢

render() { 
    // .... 
    <input className={`input-myField ${this.state.isUpdated ? 'highlight' : ''}`} /> 
    // .... 
} 

最后我建议你使用this library

+0

请注意,您无法在此处调用this.setState()。如果您需要更新状态以响应支柱更改,请改用componentWillReceiveProps()。 (https://facebook.github.io/react/docs/react-component.html#componentwillupdate) – Manolo

+0

@Manolo,这是正确的一个不应该在'componentWillUpdate'中使用'setState'。 – Panther

+0

如果我需要更新状态,你会如何调用componetWillRecieveProps? – Demon