这是一个有两个文本区域的组件。props 和 state 之间存在受控关系。这是输入的关键。注意 componentWillReceiveProps。
import React, {Component} from 'react';
import Actions from '../../flux/Actions';
let CurrentSnipDivSty = {
height: 'calc(((100% - 40px) * .4) - 3px)',
minHeight: '9.5em',
width: '100%'
};
let CurrentSnipTextAreaSty = {
backgroundColor: '#213919',
border: '1px solid #314929',
color: '#afac87',
fontSize: '1em',
height: 'calc(50% - 20px)',
overflowY: 'auto',
padding: '5px',
width: 'calc(100% - 12px)'
};
class SnipsDetailRender extends Component {
render() {
let snip = this.state.snip.snip;
let comment = this.state.snip.comment;
return (
<div id='CurrentSnipDivSty' style={CurrentSnipDivSty}>
<textarea
value={snip}
onChange={this.handleSnipChange}
style={CurrentSnipTextAreaSty} />
<textarea
value={comment}
onChange={this.handleCommentChange}
style={CurrentSnipTextAreaSty} />
</div>
);
}
}
export default class SnipsDetail extends SnipsDetailRender {
constructor() {
super();
this.state = { snip: {snip: '', comment: ''} };
}
componentWillReceiveProps = (nextProps) => {
if ((nextProps.data.snip != this.state.snip.snip) || (nextProps.data.comment != this.state.snip.comment))
this.setState({snip: nextProps.data});
}
handleSnipChange = (ev) => {
let newSnip = {snip: ev.target.value, comment: this.state.snip.comment};
this.setState({snip: newSnip});
Actions.saveSnipEdit(newSnip);
}
handleCommentChange = (ev) => {
let newSnip = {snip: this.state.snip.snip, comment: ev.target.value};
this.setState({snip: newSnip});
Actions.saveSnipEdit(newSnip);
}
}