反应负载值并允许用户更改组件内的值

时间:2018-09-10 01:03:16

标签: javascript reactjs es2017

我是React(16.4.2)的新手,我正试图了解它的工作方式。我不想使redux复杂化;我只想了解核心反应库。

我有一个应用程序,(最终在子链中)有一个input,它是一个组件RangeInput。它只是输入的包装器组件。

问题是两个部分

  1. 我应该能够(以用户身份)在范围内更改值
  2. 如果本地存储中有数据,则应在第一次加载它。这也意味着用户仍然应该能够更改/更改输入值。

现在,我只能做到其中之一。我知道我对这里的内容不了解。

需要发生什么?

谢谢, 凯莉

以下是课程:

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')
);

1 个答案:

答案 0 :(得分:0)

我认为这种情况可以大大简化:

import React from 'react';

export const RangeInput = props => (
  <input
    value={props.value}
    onChange={props.setValue} />
)

export class Application extends React.Component {
  constructor(props) {
    super(props);
    this.state = { value: -1, };
  }

  componentDidMount() {
    var val = localStorage.getItem('myVal');
    if (val) this.setState({value: val})
  }

  setValue(e) {
    this.setState({value: e.target.value})
    localStorage.setItem('myVal', e.target.value);
  }

  render() {
    return <RangeInput
      value={this.state.value}
      setValue={this.setValue.bind(this)} />;
  }
}

在这里,我们有两个组件:<RangeInput>(无状态组件)和<Application>(操作背后的大脑)。

<Application>跟踪状态,并将回调函数传递给RangeInput。然后,在按下键时,<RangeInput>将事件对象传递给该回调函数。然后,应用程序使用事件对象来更新状态和localStorage。刷新后,将从localStorage获取最后保存的值,并将其显示在输入中(如果可用)。