首页 > 解决方案 > 如何将动态 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>⬅&lt;/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>
        )
    }
}

非常感谢帮助者:]

标签: reactjsreact-router

解决方案


<Route path={`/room/:id`} component={props => { 
            return <SingleRoom room={this.state.rooms} {...props} /> 
          }} />

this.props.match.params.id您可以像在SingleRoom组件中一样访问 id


推荐阅读