我正在从事名为smart-house的小型项目。我有一个使用color,name and type
产生空间的表格。
我的问题是我找不到在index
组件动态ID中插入与我单击的房间匹配的属性<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>
)
}
}
非常感谢助手:]
答案 0 :(得分:0)
<Route path={`/room/:id`} component={props => {
return <SingleRoom room={this.state.rooms} {...props} />
}} />
您可以在this.props.match.params.id
组件中以SingleRoom
的身份访问