为什么获取refs的值的方法在DOM和Component中是不同的?

时间:2016-08-16 15:49:59

标签: reactjs material-ui ref

获得输入值后,this.refs.refsName.valuethis.refs.refsName.getValue()总是感到困惑。

这是测试代码:

import React from 'react';
import TextField from 'material-ui/TextField';
import darkBaseTheme from 'material-ui/styles/baseThemes/darkBaseTheme';
import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider';
import getMuiTheme from 'material-ui/styles/getMuiTheme';

class TestRef extends React.Component {
constructor() {
    super();
    this.handleChange = this.handleChange.bind(this);
}

handleChange() {
    console.log(this.refs.myInput.value); // correct
    console.log(this.refs.myInput.getValue()); //wrong
    console.log(this.refs.textFieldInput.value);//undefined
    console.log(this.refs.textFieldInput.getValue()); //correct
}

render() {
    return (<div>
            <input type="text" ref="myInput" onChange={this.handleChange}/>
            <MuiThemeProvider muiTheme={getMuiTheme(darkBaseTheme)}>
                <TextField id='1111' ref="textFieldInput" onChange={this.handleChange}/>
            </MuiThemeProvider>
        </div>
    );
 }
}

export default TestRef;

注意handleChange(),为什么getValue方法在DOM和material-ui组件中有所不同?

material-ui-TextField

此外,似乎refs不是获得dom或组件元素的最佳方式,是获得dom和组件元素的更好方法吗?

1 个答案:

答案 0 :(得分:0)

从组件元素获取值的最佳方法是访问传递给onChange处理函数的事件:

...create(user=User1, model_a=A, points=50)