javascript - 在 reactjs 中获取组件属性值
问题描述
所以我想做一个名字生成器,这里是数据
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>
);
}
}
我实际上有 2 个问题首先我想在 Tab 组件之后立即显示 TabContainer 组件而不使用 switch 语句我试图这样做但它得到一个错误
{dataGenerator.region.map( (section, i) => {
return (
<Tab key={section} value={i} label={section}/>
value === {i} && <TabContainer>{section}</TabContainer>
)
这就是我使用 switch 语句的原因,但我正在寻找替代方法。其次,我想从选项卡中获取属性标签,以将其用作我的 api 获取中的查询,例如“ https://uinames.com/api/?region=germany ”,因此当您单击其属性时,可以将其添加到查询中获取 api
解决方案
已经解决了
我只是添加
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 中的文档也说过,但这就是 react doc 所做的,这是我现在能想到的唯一方法,这是 getSection 代码
getSection = (e, section) => {
this.setState({
region: section
})
}
推荐阅读
- algorithm - 算法。将两个 n 位二进制数相加。这个问题的循环不变量是什么?
- java - Spring认证过程失败
- python - Python 程序 - 将人的体重从磅转换为公斤 - 1
- javascript - 如何模拟具有属性的对象作为文件路径以获取 Karma jasmine 中的信息
- javascript - 你如何从谷歌表格发送 Skype 消息?
- liquibase - SQL 格式的变更集的失败消息
- javascript - Axios 在发布时将嵌套的 JSON 数组变为空
- python - 在ubuntu中重命名用户名后conda坏了
- java - 按下按钮后 JFrame 冻结
- python-3.x - 使用 apply 修改 pandas 中的不同数据框