使用ReactJs从父元素获取子元素的点击ID

3

我正在开发一个ReactJs应用程序,现在我需要将从Main.js页面点击的ID传递给Sofa.js,根据刚刚点击的ID显示不同的信息。 我已经将我的代码格式化为PHP,我希望ReactJs有一个全局变量,就像$_GET一样。也许它存在,只是我不知道。我一直在搜索,但没有找到我要的东西。下面是代码。

未包含任何导入的Main.js代码:

export class Main extends React.Component {

    constructor(props) {
        super(props);
        this.state = {
            token: {},
            isLoaded: false,
            models: [],
            offset: offset,
            limit: limit
        };
    }

    componentDidMount() {

        /* Some code not relevant to the question, for getting API token */

        fetch('url/couch-model?offset=' + offset + '&limit=' + limit, {
            method: 'GET',
            headers: {
                'Content-Type': 'application/json',
                'Accept': 'application/json',
                'Authorization': 'JWT ' + (JSON.parse(localStorage.getItem('token')).token)
            }
        }).then(res => {
            if (res.ok) {
                return res.json();
            } else {
                throw Error(res.statusText);
            }
        }).then(json => {
            this.setState({
                models: json.results,
                isLoaded: true
            }, () => { });
        })    
    }

    render() {

        const { isLoaded, models } = this.state;

        if (!isLoaded) {

            return (
                <div id="LoadText">
                    Loading...
                </div>
            )

        } else {

            return (
                <div>

                    {models.map(model =>
                        <a href={"/sofa?id=" + model.id} key={model.id}>
                            <div className="Parcelas">
                                <img src={"url" + model.image} className="ParcImage" alt="sofa" />
                                <h1>{model.name}</h1>

                                <p className="Features">{model.brand.name}</p>

                                <button className="Botao">
                                    <p className="MostraDepois">Ver Detalhes</p>
                                    <span>+</span>
                                </button>
                                <img src="../../img/points.svg" className="Decoration" alt="points" />
                            </div>
                        </a>
                    )}

                    <PageButtons offset={offset} />

                </div>
            )
        }
    }
}

正如您所看到的,在第二个返回中,<a>发送了一个ID,尽管我不确定这是否是正确的方式。我尝试编写类似于此路径的route-js代码:/sofa/:id,但不知何故,/sofa/1中的CSS停止工作,无论ID是什么。

现在是Sofa.js代码,没有导入,只有相关代码:

export class Sofa extends React.Component {

    constructor(props) {
        super(props);
        this.state = {
            token: {},
            isLoaded: false,
            model: {}
        };
    }

    componentDidMount() {

        fetch(url + '/couch-model/1{/*this show be id clicked and sent by url*/}/', {
            method: 'GET',
            headers: {
                'Content-Type': 'application/json',
                'Accept': 'application/json',
                'Authorization': 'JWT ' + (JSON.parse(localStorage.getItem('token')).token)
            }
        }).then(res => {
            if (res.ok) {
                return res.json();
            } else {
                throw Error(res.statusText);
            }
        }).then(json => {
            this.setState({
                model: json,
                isLoaded: true
            }, () => {});
        })
    }

    render() {

        const { model, isLoaded } = this.state;

        if (!isLoaded) {

            return (
                <div id="LoadText">
                    Estamos a preparar o seu sofá!
                </div>
            )

        } else {

            return (
                <div id="Esquerda">    
                    <h2>{model.area_set.map(area => area.name)}</h2>    
                    <h1>{model.name}</h1>
                    <p>Highly durable full-grain leather which is soft and has  a natural look and feel.</p>    
                    <h3>Design</h3>
                    <h4>Hexagon</h4>
                </div>
            );

        }

    }

}

此外,这是route.js文件:

const Routes = (props) => (
    <BrowserRouter>
        <Switch>
            <Route path='/sofa/:id' component={Sofa}/>
            <Route path='/home' component={Home}/>
            <Route path='*' component={NotFound}/>            
        </Switch>
    </BrowserRouter>
);

export default Routes;
1个回答

4
我看到你没有使用(从我在示例中所看到的)react-router。我强烈推荐您使用它,因为它可以使这种情况变得非常容易处理。就像示例中一样。
const ParamsExample = () => (
  <Router>
    <div>
      <h2>Accounts</h2>
      <ul>
        <li>
          <Link to="/netflix">Netflix</Link>
        </li>
        <li>
          <Link to="/zillow-group">Zillow Group</Link>
        </li>
        <li>
          <Link to="/yahoo">Yahoo</Link>
        </li>
        <li>
          <Link to="/modus-create">Modus Create</Link>
        </li>
      </ul>

      <Route path="/:id" component={Child} />
    </div>
  </Router>
);

而子组件则通过路由注入了“match”。

const Child = ({ match }) => (
  <div>
    <h3>ID: {match.params.id}</h3>
  </div>
);

这里有一个CodeSandbox,您可以随意操作

在您的情况下,SofaChild组件。您可以在componentDidMount中使用从URL接收到的ID调用任何API。


@SofiaRibeiro,你能看到页面的完全刷新吗?检查一下页面的源代码,看看是否有CSS文件。 - João Cunha
1
@SofiaRibeiro 在 Main 页面上使用 Link 组件代替 a 标签。你可能已经相对地声明了你的 css 文件,例如 <link href="/your-file.css" />,所以当你使用 a 标签时,它实际上会刷新页面并相对搜索 css 文件。你能理解吗? - João Cunha
1
是的,我做到了!现在 CSS 工作了,非常感谢!我现在会测试其他部分 :) - soalrib
@SofiaRibeiro,你的沙发组件与子组件相同,因此你不必完全像那样做。只需根据你的情况进行调整即可。 - João Cunha
显示剩余5条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接