我有一段简单的代码,我试图使用replace prototype替换旧内容,并用新内容创建新元素。
例如
class App extends React.Component {
constructor() {
super();
this.state = {
name: 'bold'
};
}
replace = () =>{
let oldState = this.state.name;
oldState = oldState.replace(/bold/i, React.createElement('b',{ children: 'withBold'}) )
console.log(oldState)
this.setState({ name: oldState})
}
render() {
return (
<div>
<button onClick={this.replace}>Click</button><br />
{this.state.name}
</div>
);
}
}
ReactDOM.render(<App />, document.getElementById('code'));<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id='code'></div>
我已经试过document.createElement了,我得到了[object HTMLElement]
我的代码出了什么问题?
发布于 2018-07-02 09:47:53
String.prototype.replace期望替换值是字符串或函数。您正在传递一个对象(React.createElement(...))。
你的问题在这里:
oldState = oldState.replace(
/bold/i,
// The following must be a string, but you are passing in an object:
React.createElement('b',{ children: 'withBold'})
);有很多方法可以解决这个问题。就我个人而言,对于这样一个简单的例子,我只会这样写:
this.setState(prevState => ({
name: prevState.name.toLowerCase() === 'bold'
? <b>withBold</b>
: prevState.name
});https://stackoverflow.com/questions/51127542
复制相似问题