React和setState以及自动完成

时间:2016-06-24 07:25:45

标签: reactjs web-component material-ui

我使用反应和材料ui。 这是我的组件

```

import React from 'react';


import lightBaseTheme from 'material-ui/styles/baseThemes/lightBaseTheme';

import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider';
import getMuiTheme from 'material-ui/styles/getMuiTheme';
import AutoComplete from 'material-ui/AutoComplete';
// the light theme
const lightMuiTheme = getMuiTheme(lightBaseTheme);

// the autocomplete component width
const Preferencestypeahead = {
maxWidth: 600,
position:'relative',
margin:'auto'
}


export default class Preferences extends React.Component {


constructor(props) {
super(props);
this.handleUpdateInput = this.handleUpdateInput.bind();
this.state = {
  dataSource: [],
};
}

handleUpdateInput(value){
this.setState({
  dataSource: [
    value,
    value + value,
    value + value + value,
  ],
});
};

render() {
return (


    <div>
        <MuiThemeProvider muiTheme={lightMuiTheme}> 

                    <section style={Preferencestypeahead}>
                            <AutoComplete
                              hintText="Type"
                              dataSource={this.state.dataSource}
                              onUpdateInput={this.handleUpdateInput.bind(this)}
                              floatingLabelText="Search"
                              fullWidth={true}
                            />                          
                    </section>

        </MuiThemeProvider>
    </div>

    )

   }
  }

当我在自动完成中输入任何内容时,我一直没有定义setState。我哪里可能出错?当我尝试导入标签时,我也遇到了这个问题

2 个答案:

答案 0 :(得分:1)

您需要绑定到“this

这一行是问题所在:

this.handleUpdateInput = this.handleUpdateInput.bind();

将其更改为:

this.handleUpdateInput = this.handleUpdateInput.bind(this);

答案 1 :(得分:0)

由于你已经在使用ES6,你可以做到

...
onUpdateInput={(val) => this.handleUpdateInput(val)}
...

然后你不需要这样做 - &gt;构造函数中的this.handleUpdateInput = this.handleUpdateInput.bind(this);