【问题标题】:Get clicked ID from parent to child element with ReactJs使用 ReactJs 从父元素到子元素获取点击的 ID
【发布时间】:2019-01-11 02:10:05
【问题描述】:

我正在用 ReactJs 开发一个应用程序,现在我需要将点击的 ID 从 Main.js 页面传递到 Sofa.js,这将根据不同的情况显示不同的信息您刚刚单击的 ID。 我将我的 ming 全部格式化为 PHP,我希望 ReactJs 有一个像 $_GET ahah 这样的全局变量。也许是这样,我只是现在不知道。我一直在寻找,但没有找到我想要的东西。我将在下面显示代码。
不包含导入的 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>
            )
        }
    }
}

如您所见,第二个返回中的 &lt;a&gt; 发送了一个 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;

【问题讨论】:

    标签: javascript reactjs get fetch-api


    【解决方案1】:

    我发现您没有使用(从示例中我可以看到)react-router。

    我真的推荐你使用它,因为它让这种情况变得超级简单。

    this 示例

    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>
    );
    

    并且子组件已经被路由注入了匹配。

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

    Here is a CodeSandbox that you can play around with

    在您的情况下,SofaChild 组件。您可以使用从 url 收到的 id 在 componentDidMount 上调用您想要的任何 API。

    【讨论】:

    • 我在另一个名为 route.js 的文件中有 react-router,我尝试使用 /:id 但该页面中的 CSS 刚刚停止工作
    • @SofiaRibeiro 你看到页面完全刷新了吗?检查页面中的视图源,看看是否看到了 css 文件。
    • @SofiaRibeiro 使用 Link 组件代替 Main 上的 a 标签。您可能将您的 css 文件声明为相对像 因此,由于您使用的是 a 标签,它实际上会刷新页面并且 css 文件相对搜索。你明白吗?
    • 是的,我愿意!现在 CSS 可以工作了,非常感谢!我现在将测试其余的:)
    • @SofiaRibeiro 你应该有类似'localhost:3030/styles.css'的东西。那是绝对路径。您需要将其调整为您要使用的任何端口或 url。
    猜你喜欢
    • 1970-01-01
    • 2012-04-12
    • 2012-05-03
    • 1970-01-01
    • 1970-01-01
    • 2016-06-30
    • 1970-01-01
    • 2013-08-28
    • 2016-05-11
    相关资源
    最近更新 更多