我正在尝试写一个笔记/组织应用程序,我遇到了令人沮丧的错误。
这是我的组件:
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 prop中的新内容重新注释音符组件时,textarea不会更改并保留前一音符中的内容。我已经尝试使用value属性而不是defaultValue属性来处理文本区域,这样可以解决组件重新渲染时文本区域内容不会改变的问题,但是当我这样做时,我可以更长时间地输入textarea字段更新笔记
任何人都知道一种方式,我可以允许用户键入文本字段来更新注释,以及当我呈现不同的注释时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/
如果您正在使用redux,您还可以对输入的change事件触发一个动作以触发重新渲染。您可以在reducer中保留输入值。