我正在尝试编写一个记笔记/组织应用程序,但遇到了一个令人沮丧的错误。
这是我的组件:
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 属性中的新内容重新渲染笔记组件时,文本区域不会更改并保留上一个笔记的内容。我尝试使用 value 属性而不是文本区域的 defaultValue 属性,这确实解决了组件重新渲染时文本区域内容不改变的问题,但是当我这样做时,我不再能够在 textarea 字段中输入内容更新注释
有谁知道一种方法,我既可以允许用户在文本字段中键入内容来更新注释,又可以在渲染不同的注释时更改文本区域内容?
谢谢
问题在于,将值设置为 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/ https://jsfiddle.net/69z2wepo/96238/
如果您使用的是 redux,您还可以在输入的更改事件上触发一个操作来触发重新渲染。您可以将输入值保留在减速器中。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)