reactjs - 如何将动态 id 从数组传递到组件内的属性 - React
问题描述
我正在开发一个名为 smart-house 的迷你项目。我有一个生成空间的表格color,name and type
。我的问题是我无法找到一种方法来插入与我单击的房间匹配的组件动态 ID 中的index
属性。<SingleRoom />
我的 App.js:
现在是该属性index={0}
,因为我不知道如何在那里设置当前 ID。
class App extends Component {
state ={
rooms:[]
}
addRoom = (id,type,name,color) =>{
this.setState({rooms:[{id:id,type:type, name:name, color:color, devices:[]}, ...this.state.rooms]});
}
render(){
return (
<div className="App">
<Title title="Smart House" />
<Router>
<Switch>
<Route exact path="/" component={() => {return <HomePage rooms={this.state.rooms.map((item,i) => {
return <Link to={`/room/${item.name}`}><ArchiveRoom color={item.color} name={item.name} index={i} /></Link>
})} />}} />
<Route path="/addroom" component={() => {return <AddRoom add={this.addRoom} />}} />
<Route path={`/room/:id`} component={() => {
return <SingleRoom room={this.state.rooms} index={0} />
}} />
</Switch>
</Router>
</div>
)
}
}
我的 SingleRoom.js 组件
export default class SingleRoom extends Component {
constructor(props){
super(props)
this.state = {
index: props.index,
name: this.props.name,
type: this.props.type
}
}
getIndex = () =>{
this.props.index(this.state.index)
}
render() {
return (
<div className="single-room">
<Link to="/"><div className="add-room homepage-button"><button>⬅</button></div></Link>
<h4>Room name: {this.props.room[this.state.index].name}</h4>
<h4>Room type: {this.props.room[this.state.index].type}</h4>
<button className="add-room-button">Add Device</button>
</div>
)
}
}
ArchiveRoom.js 组件:
export default class ArchiveRoom extends Component {
constructor(props){
super(props)
this.state = {
index: props.index
}
}
getIndex = () => {
this.props.index(this.state.index);
}
render() {
return (
<div onClick={this.props.singleRoom} style={{backgroundColor:this.props.color, cursor:"pointer"}} className="archive-room">
<h3>{this.props.name}</h3>
</div>
)
}
}
非常感谢帮助者:]
解决方案
<Route path={`/room/:id`} component={props => {
return <SingleRoom room={this.state.rooms} {...props} />
}} />
this.props.match.params.id
您可以像在SingleRoom
组件中一样访问 id
推荐阅读
- javascript - 当用户在多页表单的特定页面上时,重力表单 Javascript 挂钩触发脚本
- java - 当控件到达回收站视图的 findViewbyId() 时,Android 应用程序崩溃?
- python - 根据两列的条件删除重复项
- awk - 使用对应文件替换模式
- r - 用另一列(国家代码)替换列值中的值
- typescript - TypeScript 获取类实例的类型
- flutter - Flutter:使用 RadioButton 从 Firestore 显示 Googlemap 标记
- ios - C++ 代码在 XCode 12 上的发布中表现不同
- powerbi - Power BI 文件未上传
- powerbi - 报表数据集结束刷新时间 PowerBI