【问题标题】:Using Link component dynamically in React-Router在 React-Router 中动态使用 Link 组件
【发布时间】:2019-05-09 07:02:15
【问题描述】:

根据存储在组件状态中的条件,我希望将呈现的特定组件包装在 Link 标记或常规 div 标记中(或者没有标记也可以!)

我目前正在做的事情似乎冗长而多余;我觉得有一种更短的方法可以编写这个组件来保持我的代码 DRY。

存储我的linkThumbnaildefaultThumbnnail 组件的两个变量几乎完全相同,除了其中一个包含在Link 组件中。

然后我在return 语句中使用三元运算符来给我所需的组件。

这里有一些伪代码作为例子:

import React, { Component } from "react";
import { Link } from "react-router-dom";

class ExampleComponent extends Component {
  state = {
    renderLink: false
  };

  render() {
    const linkThumbnail = (
      <Link
        to={{
          pathname: `/someMovieId`,
          state: 'some-data'
        }}
      >
        <div>
          <div className='movie' onClick={this.getMoviePreview}>
            <img
              src={
                poster
                  ? `https://image.tmdb.org/t/p/w300${poster}`
                  : "https://via.placeholder.com/300"
              }
              alt='something here'
            />
          </div>
        </div>
      </Link>
    );

    const defaultThumbnail = (
      <div>
        <div className='movie' onClick={this.getMoviePreview}>
          <img
            src={
              poster
                ? `https://image.tmdb.org/t/p/w300${poster}`
                : "https://via.placeholder.com/300"
            }
            alt='something here'
          />
        </div>
      </div>
    );

    //here I use a ternary operator to show the correct component...shorter method of doing this?
return this.state.renderLink ? linkThumbnail : defaultThumbnail;
  }
}

export default ExampleComponent;

【问题讨论】:

    标签: reactjs react-router react-router-v4 react-router-dom


    【解决方案1】:

    尝试创建另一个以this.state.renderLink 作为道具的组件:

    const ThumbnailLink = ({enabled, children, ...props}) => {
        if (enabled) {
            return <Link {...props}>{children}</Link>;
        } else {
            return <div>{children}</div>;
        }
    }
    
    class ExampleComponent extends Component {
        render() {
            return (<ThumbnailLink enabled={this.state.renderLink} to={{pathname: `/someMovieId`, state: 'some-data'}}>
                <div>
                    <div className='movie' onClick={this.getMoviePreview}>
                        <img
                            src={
                                poster
                                ? `https://image.tmdb.org/t/p/w300${poster}`
                                : "https://via.placeholder.com/300"
                            }
                            alt='something here'
                        />
                    </div>
                </div>
            </ThumbnailLink>);
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2020-03-28
      • 2021-11-20
      • 2021-11-05
      • 2018-01-29
      • 2019-08-07
      • 1970-01-01
      • 2019-09-15
      • 1970-01-01
      • 2019-08-11
      相关资源
      最近更新 更多