我有一个基本的表单组件,我想添加一个文本编辑器。我正在使用的文本编辑器已在应用程序的其他位置使用,因此我无法对其进行更改。
我想使文本编辑器的行为像一个“受控组件”,并以表单组件的状态将其存储在编辑器中,但是当我无法更改实际的编辑器时,我不确定如何执行此操作。
我想我需要检测编辑器组件的子代是否正在更改,并根据此状态更新状态?
如果有人能告诉我如何实现我的目标,我将非常感激。
表单组件
class ContactForm extends React.Component {
constructor(props) {
super(props);
this.state = {
name: '',
email: '',
editorBody: ''
};
this.handleChange = this.handleInputChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
this.handleEditorChange = this.handleEditorChange.bind(this);
}
handleInputChange(event) {
const target = event.target;
const value = target.type === 'checkbox' ? target.checked : target.value;
const name = target.name;
this.setState({
[name]: value
});
console.log('Change detected. State updated' + name + ' = ' + value);
}
handleEditorChange(event) {
// Here I want to update the state with the value from the Texteditor
}
handleSubmit(event) {
alert(
'A form was submitted: ' + this.state.name + ' // ' + this.state.email
);
event.preventDefault();
}
render() {
return (
<div>
<form onSubmit={this.handleSubmit}>
<div className="form-group">
<label for="nameImput">Name</label>
<input
type="text"
name="name"
value={this.state.name}
onChange={this.handleChange}
className="form-control"
id="nameImput"
placeholder="Name"
/>
</div>
<div className="form-group">
<label for="emailImput">Name</label>
<input
name="email"
type="email"
value={this.state.email}
onChange={this.handleChange}
className="form-control"
id="emailImput"
placeholder="email@domain.com"
/>
</div>
<div className="form-group">
<TextEditor />
</div>
<input type="submit" value="Submit" className="btn btn-primary" />
</form>
</div>
);
}
}
编辑器组件
const TextEditor = (props) => {
const { initialTextValue = 'A line of text in a paragraph' } = props;
const initialValue = Value.fromJSON({
document: {
nodes: [
{
object: 'block',
type: 'paragraph',
nodes: [
{
object: 'text',
text: initialTextValue
}
]
}
]
}
});
const [value, updateValue] = useState(initialValue);
const editor = useRef(null);
const menu = useRef(null);
const onChange = ({ value: newValue }) => {
updateValue(newValue);
};
return (
<div {...props}>
<Container>
<Toolbar>
<ToobarButtonGroup>
{Object.keys(icons).map((icon, i) => {
return (
<ToolbarButton
key={i}
onPointerDown={() => editor.current.toggleMark(icon)}
type="button"
>
<FontAwesomeIcon icon={icons[icon]} />
</ToolbarButton>
);
})}
</ToobarButtonGroup>
</Toolbar>
<SubContainer>
<Editor
renderBlock={renderBlock}
renderMark={renderMark}
renderInline={renderInline}
value={value}
onChange={onChange}
plugins={plugins}
commands={commands}
queries={queries}
ref={editor}
/>
</SubContainer>
</Container>
</div>
);
};