2016-10-26 5 views
2

私は作業しているWebアプリケーション内に単純なコンポーネントを持っていますが、this.propsの値に基づいてこのコンポーネント内の要素をレンダリングできる方法があるかどうかは疑問でした。項目。が条件に基づいてJSX要素をレンダリングする

render:function(){ 
     return(
    code blah blah... 

if (this.props.info = "nothing"){ 
    <div className="panel-body">{this.props.info.tagline}</div> 
    } 

    ...code blah blah 

しかし、私はレンダリング機能自体をwithing JavaScriptを記述することはできません:私はこのような何かをできるようにしたかった

var React = require("react"); var actions = require("../actions/SchoolActions"); 

module.exports = React.createClass({ 
    deleteSchool: function(e){ 
     e.preventDefault(); 
     actions.deleteSchool(this.props.info); 
    }, 
    render:function(){ 
     return(
      <div className="panel panel-default"> 
       <div className="panel-heading"> 
        {this.props.info.name} 
        <span className="pull-right text-uppercase delete-button" onClick={this.deleteSchool}>&times;</span> 
       </div> 
       <div className="panel-body">{this.props.info.tagline}</div> 
      </div> 
     ) 
    } }) 

は、ここに私のJSXです。誰も私がこれをどうやってできるか知っていますか?どんな助けや助言もありがとうございます、事前にありがとうございます。

答えて

2

あなたがにあなたのコンポーネントをchaageでき

render(){ 
    if(something){ 
     return(<MyJsx1/>) 
    }else{ 
     return(<MyJsx2/>) 
    } 
} 

適切なJSX条件付きで使用ifを使用してレンダリングして返すことができます。

 render:function(){ 
      return(
       <div className="panel panel-default"> 
        <div className="panel-heading"> 
         {this.props.info.name} 
         <span className="pull-right text-uppercase delete-button" onClick={this.deleteSchool}>&times;</span> 
        </div> 
        {this.props.info = "nothing"? 
        (<div className="panel-body">{this.props.info.tagline}</div>) 
        :null} 

       </div> 
      ) 
     } }) 

https://facebook.github.io/react/docs/conditional-rendering.html

+0

私は自分のコンポーネントにこれをどのように実装するのだろうかと思っています。 –

+0

@danjonescidtrixあなたのコンポーネントを完全に投稿する – StateLess

+0

私の質問の先頭に全コンポーネントが表示されます –

0

シングルラインの例を

{(this.state.hello) ? <div>Hello</div> : <div>Goodbye</div>} 

または

{(this.state.hello) ? <div>Hello</div> : false} 
1

私は、多くの場合、メインで混乱を避けるために、これにに明示的な関数を作成をレンダリング:多くの場合

var ChildComponent = React.createClass({ 
    render: function() { 
     return (<p>I am the child component</p>) 
    } 
}); 

var RootComponent = React.createClass({ 

    renderChild: function() { 
    if (this.props.showChild === 'true') { 
     return (<ChildComponent />); 
    } 

    return null; 
    }, 

    render: function() { 
    return(
     <div> 
     { this.renderChild() } 
     <p>Hello World!</p> 
     </div> 
    ) 
    } 
}); 
+0

ああ、それはかなりきちんとした男です。私はこれを念頭に置いておきます。 –

-1

http://reactkungfu.com/2016/11/dynamic-jsx-tags/

を使用する開発者に反応JSXでは、動的なJSXタグ を作成する方法が明確ではありません。つまり、 入力かtextareaかdivかspan(または何か他のもの)であるかどうかをハードコーディングする代わりに、 を変数に入れておきます。

関連する問題