我正在尝试编写一个记笔记/整理应用程序,但我遇到了一个令人沮丧的错误。
这是我的组件:
import React from 'react';
const Note = (props) => {
let textarea, noteForm;
if (props.note) {
return (
<div>
<button onClick={() => {
props.handleUpdateClick(props.selectedFolderId, props.selectedNoteId, textarea.value);
}}>
Update
</button>
<textarea
defaultValue={props.note.body}
ref={node => {textarea = node;}}
/>
</div>
);
} else {
return <div></div>;
}
};
export default Note;
就目前而言,每当我在笔记之间切换并使用 note.body 属性中的新内容重新呈现笔记组件时,textarea 不会更改并保留前一个笔记的内容。我已经尝试对文本区域使用 value 属性而不是 defaultValue 属性,这确实解决了组件重新呈现时文本区域内容不更改的问题,但是当我这样做时,我不再能够在 textarea 字段中键入更新笔记
有没有人知道我可以允许用户在文本字段中键入以更新注释以及在呈现不同注释时更改文本区域内容的方法?
谢谢
最佳答案
问题是为你的 prop 设置值会导致组件的所有重新渲染都使用相同的 prop,因此新文本被删除。一种解决方案是将文本保留在组件的本地状态中。要同时收听 Prop 变化,您可以在收到新 Prop 时设置状态。
const Note = React.createClass({
getInitialState() {
return {
text : this.props.note.body
}
},
componentWillReceiveProps: function(nextProps) {
if (typeof nextProps.note != 'undefined') {
this.setState({text: nextProps.note.body });
}
},
render() {
if (this.props.note) {
return (
<div>
<button onClick={(e) => {
// Fire a callback that re-renders the parent.
// render(this.textarea.value);
}}>
Update
</button>
<textarea
onChange={e => this.setState({ text : e.target.value })}
value={this.state.text}
ref={node => {this.textarea = node;}}
/>
</div>
);
} else {
return <div></div>;
}
}
});
https://jsfiddle.net/69z2wepo/96238/
如果您使用的是 redux,您还可以对输入的更改事件触发一个操作以触发重新渲染。您可以在 reducer 中保留输入值。
关于html - ReactJS 组件文本区域未在状态更改时更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41775004/