【发布时间】:2019-02-14 10:03:37
【问题描述】:
我是 React (16.4.2) 的新手,我正在尝试了解它的工作方式。我不想用redux 使事情复杂化;我只想了解核心反应库。
我有一个应用程序,并且(最终在子链下)有一个input,它是一个组件,RangeInput。它只是一个输入的包装组件。
问题分两部分
- 我应该能够更改范围内的值(作为用户)
- 如果本地存储中有数据,则应在第一时间加载。这也意味着用户应该仍然能够更改/更改输入值。
现在有了这个,我看到只能做另一个。我知道我不明白这里的东西。
需要做什么?
谢谢, 凯莉
以下是课程:
export class RangeInput extends React.Component {
constructor(props) {
super(props);
this.ds = new DataStore();
this.state = {
value: props.value
};
}
static getDerivedStateFromProps(props, state) {
console.log('props', props, 'state', state);
if (props.value !== state.value) {
return {value: props.value};
}
return null;
}
onChange(event) {
const target = event.target;
this.setState({
value: target.value
});
if (this.props.onChange) {
this.props.onChange({value: target.value});
}
}
onKeyUp(event) {
if (event.keyCode !== 9) {
return;
}
const target = event.target;
if (this.props.onChange) {
this.props.onChange({value: target.value});
}
}
render() {
return <div>
<input type="number" value={this.state.value}
onChange={this.onChange.bind(this)}
onKeyUp={this.onKeyUp.bind(this)}/>
</div>;
}
}
const DATA_LOAD = 'load';
export class Application extends React.Component {
constructor() {
super();
this.state = {
value: -1,
load = DATA_LOAD
};
}
componentDidMount() {
if (this.state.load === DATA_LOAD) {
this.state.load = DATA_CLEAN;
const eco = this.ds.getObject('the-app');
if (eco) {
this.setState({value: eco});
}
}
}
render(){
return <RangeInput value={this.state.value} />;
}
}
ReactDOM.render(
<Application/>,
document.getElementById('root')
);
【问题讨论】:
-
好多代码好像漏掉了,能不能补一下或者做个沙盒?
-
范围内是什么意思?您作为道具传递给 RangeInput 的值是什么,为什么?还有一件事永远不会直接在渲染中进行绑定,而是在构造函数中进行
-
显然有更多的属性被发送到这个组件,
RangeInput,但核心是设置,value是问题所在。唯一要补充的是,Application可以保存到本地存储,但只有在实际单击submit时,这意味着没有“智能保存”功能
标签: javascript reactjs ecmascript-2017