reactjs - React 类组件中的不同状态对象?
问题描述
我正在尝试在类组件中使用功能组件,但无法使其工作。 文档指出应该有两个不同的状态对象。
The component has two states that can be controlled:
the "value" state with the value/onChange props combination. This state represents the value selected by the user, for instance when pressing Enter.
the "input value" state with the inputValue/onInputChange props combination. This state represents the value displayed in the textbox.
我怎样才能把它写成一个类组件?
import React from 'react';
import TextField from '@material-ui/core/TextField';
import Autocomplete from '@material-ui/lab/Autocomplete';
const options = ['Option 1', 'Option 2'];
export default function ControllableStates() {
const [value, setValue] = React.useState(options[0]);
const [inputValue, setInputValue] = React.useState('');
return (
<div>
<div>{`value: ${value !== null ? `'${value}'` : 'null'}`}</div>
<div>{`inputValue: '${inputValue}'`}</div>
<br />
<Autocomplete
value={value}
onChange={(event, newValue) => {
setValue(newValue);
}}
inputValue={inputValue}
onInputChange={(event, newInputValue) => {
setInputValue(newInputValue);
}}
id="controllable-states-demo"
options={options}
style={{ width: 300 }}
renderInput={(params) => <TextField {...params} label="Controllable" variant="outlined" />}
/>
</div>
);
}
这是我的解决方案。如您所见,与功能示例不同,类组件没有默认值。
import React from 'react';
import TextField from '@material-ui/core/TextField';
import Autocomplete from '@material-ui/lab/Autocomplete';
export class ControllableStates2 extends React.Component {
constructor(props) {
super(props);
const symbols = [
'BTCUSDT',
'ETHUSDT'
];
this.state = {
value: symbols[0],
inputValue: '',
options: symbols
};
}
render() {
return (
<div>
<div>{`value: ${this.state.value !== null ? `'${this.state.value}'` : 'null'}`}</div>
<div>{`inputValue: '${this.state.inputValue}'`}</div>
<br/>
<Autocomplete
value={this.state.value}
onChange={(event, newValue) => {
this.state.value = newValue;
}}
inputValue={this.state.inputValue}
onInputChange={(event, newInputValue) => {
this.state.inputValue = newInputValue;
}}
id="controllable-states-demo"
options={this.state.options}
style={{width: 300}}
renderInput={(params) => <TextField {...params} label="Controllable" variant="outlined"/>}
/>
</div>
);
}
}
解决方案
错误出现在这些部分
onChange={(event, newValue) => {
this.state.value = newValue;
}}
应该
onChange={(event, newValue) => {
this.setState({...this.state, value: newValue});
}}
推荐阅读
- angular - 没有将“exportAs”设置为“ngForm”的指令 - 是的,我看过其他帖子
- youtube-data-api - Youtube API v3 从给定频道获取每个视频 ID
- ruby-on-rails - Rails - 增量构建嵌套表单的连接记录
- ruby-on-rails - Rails 数据库连接中的简单线程
- apache - 如何配置 tomcat 以请求凭据而不进行身份验证?
- google-chrome - Chrome 最新版本不能自动启动 Youtube
- php - PHP - 查询变量 - 不工作
- python - Python terminal in html?
- javascript - 以正确的方式扩展扩展类中的默认选项
- angular - Angular error : Can't bind to 'ngForFrom' since it isn't a known property of 'a'