按键创建活动

时间:2016-01-13 00:44:55

标签: javascript reactjs redux

我尝试创建一个组件,只要文本输入到输入字段中,该组件就会触发事件。但是,当我刷新页面或从另一个组件发送事件时,事件似乎只会触发。即便如此,它只会发射一次。

如何在输入中按下键时创建仅调度事件的组件?如何确保递增Counter组件并不会触发onKeyPress事件?

// Reducers
const counter = (state = 0, action) => {
    switch (action.type) {
        case 'INCREMENT':
            return state + 1;
        case 'DECREMENT':
            return state - 1;
        default:
            return state;
    }
};


// Store
const reducer = combineReducers(reducers);
const store = createStore(reducer);


// Components
const Counter = ({ value, onIncrement, onDecrement }) => (
    <div>
        <h1>{value}</h1>
        <button onClick={onIncrement}>+</button>
        <button onClick={onDecrement}>-</button>
    </div>
);

class TestComponent extends Component {
    render() {
        return (
            <input onKeyPress={ console.log('key pressed') } />
        );
    };
};


// Render
const render = () => {
  ReactDOM.render(
    <div>
        <Counter
          value={ store.getState().counter }
          onIncrement={ () => store.dispatch({ type: 'INCREMENT' }) }
          onDecrement={ () => store.dispatch({ type: 'DECREMENT' }) }
        />
        <TestComponent />
    </div>,
    document.getElementById('root')
  );
};
store.subscribe(render);
render();

1 个答案:

答案 0 :(得分:1)

使您的onKeyPress值成为一个函数。即。

<input onKeyPress={(event) => console.log('key pressed', event)} />