所以我想做一个名字生成器,这里的数据
export const dataGenerator = {
gender: ["Male", "Female"],
region: ["France", "Germany", "Italy", "Korea", "Russia"]
}
我的组件:
class NameGenerator extends React.Component{
constructor(props){
super(props);
this.state={
value: 0,
name: "",
surname: "",
gender: "",
region: "",
}
this.onClick = this.onClick.bind(this);
}
// handle change
handleChange = (e, value) => {
this.setState({ value})
}
onClick(e){
if(e.keyCode === 32){
fetch('https://uinames.com/api/')
.then( res => res.json())
.then(namedata => {
this.setState({
name: namedata.name,
surname: namedata.surname
})
})
}
}
componentDidMount(){
fetch('https://uinames.com/api/')
.then( res => res.json())
.then( namedata => {
this.setState({
name: namedata.name,
surname: namedata.surname,
gender: namedata.gender,
region: namedata.region
})
});
window.addEventListener('keyup', this.onClick, false);
}
//Display Select Region
selectRegion = (value) => {
switch(value){
case 0:
return <TabContainer>{this.state.name} {this.state.surname}</TabContainer>;
case 1:
return <TabContainer>Germany</TabContainer>;
case 2:
return <TabContainer>Italy</TabContainer>;
case 3:
return <TabContainer>Korea</TabContainer>;
case 4:
return <TabContainer>Russia</TabContainer>;
default:
return 'error'
}
};
render(){
const { dataGenerator } = this.props;
const { value} = this.state;
return(
<div>
<AppBar position="static" color="default">
<Tabs
value={value}
onChange={this.handleChange}
indicatorColor="primary"
textColor="primary"
fullWidth
>
{dataGenerator.region.map( (section, i) => {
return (
<Tab key={section} value={i} label={section}/>
)
})}
</Tabs>
{this.selectRegion(value)}
<div>
</div>
</AppBar>
</div>
);
}
}
我实际上有两个问题 首先,我想在Tab组件之后立即显示TabContainer组件,而不使用switch语句,但我尝试这样做,但是却收到错误
{dataGenerator.region.map( (section, i) => {
return (
<Tab key={section} value={i} label={section}/>
value === {i} && <TabContainer>{section}</TabContainer>
)
这就是为什么我使用switch语句,但是我正在寻找替代方法的原因。 其次,我想从选项卡中获取属性标签,以将其用作“ https://uinames.com/api/?region=germany”这样的api提取中的查询,因此,当您单击其属性时,将其添加到提取api中的查询中
答案 0 :(得分:0)
已经解决了
我只需添加
onClick = {(((e)=> this.getSection(e,section))}
在
{dataGenerator.region.map( (section, i) => {
return (
<Tab key={section} value={i} label={section} onClick={((e) => this.getSection(e, section))}/>
)
有人说您不应该像匿名文档那样放置匿名函数,但这就是react文档所做的事情,那是我现在唯一想到的方法,这就是getSection代码
getSection = (e, section) => {
this.setState({
region: section
})
}