【问题标题】:Set button made in js to route to another page in React在 js 中设置按钮以路由到 React 中的另一个页面
【发布时间】:2021-09-30 02:00:28
【问题描述】:

我正在 for-loop 中制作 div 元素,并希望将每个 div 分配给带有他的 id/campaign 页面。 p>

我想在 div 上单击以转到 "/campaign/id" 页面并将 id 传递给 Campaign 组件。

class Home extends Component{
   ...
   async printCampaigns(){
        const totalSupply = 5
        const mainDiv = document.getElementById("myID")
            for(var i = 0;i<totalSupply;i++){
                const _div = document.createElement('div')
                _div.onclick = function() {
                    //I want this onclick to go to ("/campaign/" + _div.id)
                }
                mainDiv.appendChild(_div)
            }
    }
   ...
}

这是我的路由器代码

const Routing = () => {
    return(
        <Router>
            <Header/>
            <Switch>
                <Route exact path="/" component={Home} />
                <Route path="/campaign/:id" component={Campaign} />
            </Switch>
        </Router>
    )
}

ReactDOM.render(<Routing />, document.getElementById('root'));

在 /campaign/id 上打开此类并有权访问该 id

class Campaign extends Component{
}

【问题讨论】:

    标签: javascript html reactjs react-router


    【解决方案1】:

    您可以使用 setAttribute 函数设置 _div id 和 window.location.href 用于 onClick 事件 像这样:

      async printCampaigns(){
            const totalSupply = 5
            const mainDiv = document.getElementById("myID")
                for(var i = 0;i<totalSupply;i++){
                    const _div = document.createElement('div');
                    _div.setAttribute("id", i);
                    _div.onclick = function() {
                        window.location.href="/campaign/"+ i;
                    }
                    mainDiv.appendChild(_div)
                }
        }
    

    【讨论】:

    • 行得通,谢谢。我使用window.location.pathname.split("/").pop() 来获取其他组件中的 id。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-06
    • 2021-08-02
    • 2016-09-14
    • 2015-05-28
    • 2021-12-06
    相关资源
    最近更新 更多