Conditionally linking with react-router Link

后端 未结 3 628
孤城傲影
孤城傲影 2021-01-12 08:21

I have a situation in my React component which is: i want some elements to be wrappend in a Link component if this.props.isComingFromModal is false

3条回答
  •  死守一世寂寞
    2021-01-12 08:38

    You're right to want to try to avoid repetition in your JSX. I have a couple of strategies I use for this type of situation.

    One option uses the fact that Link is just a ReactComponent object, and can be assigned to any variable. You can put a line like this at the beginning of your render method:

    var ConditionalLink = !this.props.isComingFromModal ? Link : React.DOM.div;
    

    and then just render your content wrapped in the ConditionalLink component:

    return (
        
            
            
    ...
    );

    When your condition is true, ConditionalLink will be a reference to Link; when the condition is false it will be a simple

    .

    Another option you might want to try is to create the content you want to render inside of the Link (or not inside the link) elsewhere, and then do essentially what you're doing above:

    var content = (
        
    All your content
    ); return ( {content} {content} );

    You could also create a function or method to return the content- or put it entirely in a new component.

    Finally, to actually answer your question- Yes, you can make a link component that works the way you want! One of the great things about React is that it's really easy to remix existing components. If you want a conditional Link, just create a component that returns either {this.props.children} or {this.props.children} based on the value of a prop.

提交回复
热议问题