下午好!我开始处理react-redux
并在某一时刻陷入困境。我不知道如何访问dispatch
组件本身内部的方法。问题是,我正在尝试从表单字段中获取数据。在mapDispatchToProps
方法中,我无法得到refs
. 请告诉我如何正确执行此操作?
例如:index.js
import React from 'react'
import ReactDOM from 'react-dom'
import { Provider } from 'react-redux'
import store from './store'
import App from './App'
const rootElement = document.getElementById('root')
ReactDOM.render(
<Provider store={store}>
<App />
</Provider>,
rootElement
)
代码是在这里输入的,可能在语法中打错了... App.js
// imports ...
class App extends React.Component {
constructor(props) {
super(props);
this.title = React.createRef();
this.message = React.createRef();
}
// Idea 1
onSubmitHandler_1 = e => {
e.preventDefault();
// how get store.dispatch({type:"UPDATE", this.title.current.value, this.message.current.value});
};
render() {
return (
<form onSubmit={this.props.onSubmitHandler_1 OR this.onSubmitHandler_2}>
<input type="text" ref={this.title} name="title" />
<input type="password" ref={this.message} name="password" />
<button>Send</button>
</form>
);
}
}
const mapDispatchToProps = (state, ownProps) => {
return {};
};
// Idea 1;
const mapDispacthTOProps = (dispatch, ownProps) => {
return {
onSubmitHandler_2: e => {
e.preventDefault();
// oh... no!!! bad idea...
// let inputTitle = e.target.querySelector('[name="title"]');
// let inputTitle = e.target.querySelector('[name="password"]')
dispatch({ type: "UPDATE" }); //... ???? refs
// how get access to fields or refs??
}
};
};
export default connect(mapDispatchToProps, mapDispacthTOProps)(App);