2015-11-21 9 views
17

मैं दुनिया प्रतिक्रिया करने के लिए नया हूँ और मैं इस तरह लाइन है:ऑनक्लिक नए प्रतिक्रिया घटक प्रस्तुत नहीं करता है।

<Button onClick={() => console.log("hello")}>Button</Button> 

और पर आप hello कंसोल पर मुद्रित मिल जाएगा पर क्लिक करें।

<Button onClick={() => <NewComponent />}>Button</Button> 

अब बटन पर क्लिक करने पर ही, मैं उम्मीद NewComponent प्रदान करने की: अब लाइन के लिए बदल जाते हैं। लेकिन ऐसा नहीं है।

मुझे यकीन नहीं है, ऐसा क्यों है। ध्यान दें कि मेरे पास उपरोक्त कोड render विधि में है।

+0

यह कैसे काम करता है बस नहीं है यही कारण है कि। घटक को प्रस्तुत करने के लिए आप कहां से उम्मीद करेंगे? उसी पृष्ठ पर –

+0

। – batman

+0

लेकिन कहाँ? बटन के ऊपर? बटन के नीचे? बटन के अंदर? * 'OnClick' विशेषता के अंदर? * कहीं और? वर्तमान में आपका क्लिक हैंडलर कुछ फ़ंक्शन() {React.createElement (...) जैसा है; } '। यह उस तत्व के साथ कुछ भी नहीं करता है जो बनाया गया था। –

उत्तर

31

शायद आप एक राज्यव्यापी घटक चाहते हैं जो क्लिक करने के बाद बटन के बगल में स्थित अन्य घटक दिखाता है। तुम सब करने की ज़रूरत को ट्रैक किया गया है या बटन क्लिक किया गया था:

class MyComponent extends React.Component { 
    constructor(props) { 
    super(props); 
    this.state = { 
     showComponent: false, 
    }; 
    this._onButtonClick = this._onButtonClick.bind(this); 
    } 

    _onButtonClick() { 
    this.setState({ 
     showComponent: true, 
    }); 
    } 

    render() { 
    return (
     <div> 
     <Button onClick={this._onButtonClick}>Button</Button> 
     {this.state.showComponent ? 
      <NewComponent /> : 
      null 
     } 
     </div> 
    ); 
    } 
} 
+0

नमस्ते। अगर मैं एक ही पृष्ठ पर केवल न्यूकंपोनेंट लोड करना चाहता हूं तो सभी को ओवरराइट करना प्रतिक्रिया राउटर का उपयोग किए बिना अन्य घटक? –

2

यहाँ कार्रवाई में यह दिखाने के लिए एक CodePen है।

एचटीएमएल

<div id="root">loading...</div> 

JSX

class NewComponent extends React.Component { 
    render() { 
    return (
     <div {...this.props}> 
     new component 
     </div> 
    ); 
    } 
} 

class Button extends React.Component { 
    render() { 
    return (
     <button {...this.props}> 
     click 
     </button> 
    ); 
    } 
} 

class App extends React.Component { 
    constructor() { 
    super(); 

    this.state = { 
     clicked: false 
    }; 

    this.handleClick = this.handleClick.bind(this); 
    } 

    handleClick() { 
    this.setState({ 
     clicked: true 
    }); 
    } 

    render() { 
    return (
     <div> 
     <Button onClick={this.handleClick} /> 
     {this.state.clicked ? <NewComponent /> : null} 
     </div> 
    ); 
    } 
}; 

React.render(
    <App />, 
    document.getElementById("root") 
); 
+0

एक पेन ने कभी इतना मदद नहीं की। मैं प्रतिक्रिया के बारे में सशर्त प्रतिपादन मुद्दा प्राप्त करना शुरू कर रहा हूं :) धन्यवाद! –

संबंधित मुद्दे