简体   繁体   English

危险地反应 SetInnerHTML 不重新呈现内容

[英]react dangerouslySetInnerHTML not re-rendering content

Here's my setup:这是我的设置:

string-file.properties字符串文件.properties

someKey=This is my <span class="hello">{0}</span> string!

react-file.jsx反应文件.jsx

import stringAPI from 'string-file';    

class MyComponent extends Component {

    get content() {
        return { __html: stringAPI.someKey(this.props.word) };
    }

    render() {
        return (
            <span dangerouslySetInnerHTML={this.content} />
        );
    }
}

The argument to stringAPI.someKey get substituted for {0} in the string file and then the final html string is returned. stringAPI.someKey的参数被替换为字符串文件中的{0} ,然后返回最终的 html 字符串。 My issue is that this.props.word is being updated while MyComponent is not being updated.我的问题是this.props.word正在更新,而MyComponent没有更新。

I read somewhere that dangerouslySetInnerHTML tells React that it doesn't need to watch the state of the component that the html is rendered in. If that's true, then I still need a way to do what I'm trying to do.我在某处读到 dangerouslySetInnerHTML 告诉 React 它不需要监视 html 在其中呈现的组件的 state。如果这是真的,那么我仍然需要一种方法来做我想做的事情。

Set the string as state. 将字符串设置为state。 When receive new props ( componentWillReceiveProps ) do a setState . 当收到新的道具( componentWillReceiveProps )时,请执行setState This should rerender the component. 这应该重新呈现组件。 If that is not working make sure a unique key is set when the string changes. 如果这样不起作用,请确保在更改字符串时设置了唯一键。 This also forces a rerender 这也迫使重新提交

After adding unique key on div it's working fine. 在 div 上添加唯一键后,它工作正常。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM