React 修改 Textarea 值 [英] React Modifying Textarea Values
问题描述
我正在做一个基本上是记事本的项目.尽管在进行 ajax 调用时更新
I am working on a project which is basically notepad. I am having problems though updating the <textarea>'s value when an ajax call is made. I tried setting the textarea's value property but then no changes to its value can be made. How can I make it so on a state change the textarea's value changes and can be edited.
我的代码如下.
在父类中
<Editor name={this.state.fileData} />
在编辑器类中
var Editor = React.createClass({
render: function() {
return (
<form id="noter-save-form" method="POST">
<textarea id="noter-text-area" name="textarea" value={this.props.name}></textarea>
<input type="submit" value="Save" />
</form>
);
}
});
我不能使用 defaultValue 因为 textarea 的值在页面加载时未知,当我尝试将数据放在 textareas 之间时什么也没有发生.我希望它在状态更改时采用状态值,但可以在两者之间进行编辑.
I can't use defaultValue because the value of the textarea is not known on page load and when I try and put the data between the textareas nothing happens. I would like it to take the state value whenever the state changes but have it editable in between.
谢谢
编辑
我设法使用 jQuery 让它工作,但想在 React 中完成它,我在渲染之前调用了它:
I managed to get it working using jQuery but would like to do it in React instead, I called this before render:
$('#noter-text-area').val(this.props.name);
推荐答案
我认为你想要一些类似的东西:
I think you want something along the line of:
家长:
<Editor name={this.state.fileData} />
var Editor = React.createClass({
displayName: 'Editor',
propTypes: {
name: React.PropTypes.string.isRequired
},
getInitialState: function() {
return {
value: this.props.name
};
},
handleChange: function(event) {
this.setState({value: event.target.value});
},
render: function() {
return (
<form id="noter-save-form" method="POST">
<textarea id="noter-text-area" name="textarea" value={this.state.value} onChange={this.handleChange} />
<input type="submit" value="Save" />
</form>
);
}
});
这基本上是 https://facebook.github 上提供的示例的直接副本.io/react/docs/forms.html
React 16.8 更新:
import React, { useState } from 'react';
const Editor = (props) => {
const [value, setValue] = useState(props.name);
const handleChange = (event) => {
setValue(event.target.value);
};
return (
<form id="noter-save-form" method="POST">
<textarea id="noter-text-area" name="textarea" value={value} onChange={handleChange} />
<input type="submit" value="Save" />
</form>
);
}
Editor.propTypes = {
name: PropTypes.string.isRequired
};
这篇关于React 修改 Textarea 值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!