简体   繁体   中英

How to properly bind onChange callback to 'this' with ReactJS, Redux, and ES2015?

I'm learning ReactJS and Redux, and I cant figure out how to get access to my TextField instance while binding it's onChange callback to this .

(I'm using material-ui for this example, but I would encounter quite the same problem without it)

import React, {Component} from 'react';
import { connect } from 'react-redux';
import { setDataValue } from './actions/data';
import TextField from 'material-ui/lib/text-field';
import Paper from 'material-ui/lib/paper';

export class DataInput extends Component {
    constructor(props){
        super(props);
    }

    handleTextChange() {
        this.props.setDataValue(document.getElementById('myField').value);
    }

    render(){
        return (
            <Paper style={{
                width: '300px',
                margin: '10px',
                padding: '10px'
            }}>
                <TextField 
                  id='myField'
                  defaultValue={this.props.data.value}
                  onChange={this.handleTextChange.bind(this)} />
            </Paper>
        );
    }
}

export default connect(
  (state) => ({data: state.data}),
  {setDataValue}
)(DataInput);

I'm using a solution that I find ugly (not reusable => not very 'component-friendly') by setting an id on my TextField, and accessing its value with document.getElementById('myField').value

How could I get rid of this id , and accessing it with something like textFieldRef.value inside my callback ?

I tried without .bind(this) , which gives me access to my TextField instance through this , but I can no longer access my this.props.setDataValue() function since this isn't binded to my class context.

Thank you !

Avoid using calls like document.getElementById within a React component. React is already designed to optimise expensive DOM calls, so you're working against the framework by doing this. If you want to know how reference DOM nodes in React, read the docs here .

However, in this situation you don't actually need references. Placing a ref (or an ID) on TextField isn't necessarily going to work. What you're referencing is a React element, not a DOM node.

Instead, make better use of the onChange callback. The function passed to onChange is called with an event argument. You can use that argument to get the input value. (see React's event system .)

Your event handler should look like this:

handleTextChange(event) {
    this.props.setDataValue(event.target.value);
}

And your TextField should look like this:

<TextField 
    value={this.props.data.value}
    onChange={event => this.handleTextChange(event)}
/>

Note: Use value NOT defaultValue .

Using state along with Redux is a bad style. So this is a design issue of the code.

Redux was meant to be used along with functional components and not class style ones.

I suggest using functional component and pass syntetic event as a parameter to onChange function like this:

const mapDispatchToProps = (dispatch) => {
return {
    onChange: (value) => {
        dispatch(changeAction(value))
    }
}

and then use something like this inside the element:

<input onChange={ (e) => onChange(e.target.value)}

You can also pass elements own properties:

const mapDispatchToProps = (dispatch) => {

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM