【问题标题】:Bind text input value on change event - React Native + Redux在更改事件上绑定文本输入值 - React Native + Redux
【发布时间】:2018-07-20 08:06:49
【问题描述】:

我在 React Native 和 Redux 中创建表单。我添加了TextInput 并想在Reducer 中更改该字段的状态。我有一个麻烦,因为我不知道如何将(change) => this.setState({change}) 函数添加到我的 Redux 架构中。我使用组合减速器并且不知道如何绑定该值。 简而言之,我需要在更改功能上获得TextInput 的默认行为,但我必须使用 Redux 来做到这一点。

Form.js

const mapDispatchToProps = dispatch => {
  return {
      changeNameInput: () => dispatch({type: 'CHANGE_NAME_INPUT'})
  };
};

const mapStateToProps = state => {
  return {
      change: state.changeNameInput.change
  };
};

class Form extends React.Component {
  render() {
    return (
      <View>
         <FormLabel>Name</FormLabel>
         <TextInput
            onChangeText={this.props.changeNameInput}
            value={this.props.change}
        />
      </View>
    );
  }
}

Reducer.js

const initialState = {
    change: 'Your name'
   };

   const changeinputReducer = (state = initialState, action) => {
     switch (action.type) { 
       case 'CHANGE_NAME_INPUT':

  //Problem

         return {...state, change: '????' };
        default:
         return state;
     }
   };

   export default changeinputReducer;

【问题讨论】:

    标签: javascript forms reactjs redux


    【解决方案1】:

    为了从TextInput传递值到reducer,你需要改变dispatch函数:

    const mapDispatchToProps = dispatch => {
      return {
          changeNameInput: (text) => dispatch({type: 'CHANGE_NAME_INPUT', text})
      };
    };
    

    并在你的减速器中将其更改为

    const changeinputReducer = (state = initialState, action) => {
         switch (action.type) { 
           case 'CHANGE_NAME_INPUT':
    
      //Solution
    
             return {...state, change: action.text };
            default:
             return state;
         }
       };
    

    希望成功..

    【讨论】:

    • 太棒了。如果我使用onChangeText={this.props.changeNameInput.bind(this)}会有什么不同
    猜你喜欢
    • 2018-04-16
    • 2020-11-08
    • 2019-05-03
    • 1970-01-01
    • 2010-12-23
    • 1970-01-01
    • 2018-07-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多