खोज…


टिप्पणियों

React.createClass को React.createClass में हटा React.createClass गया था और v16 में हटाए जाने की उम्मीद थी। उन लोगों के लिए एक ड्रॉप-इन प्रतिस्थापन पैकेज है जो अभी भी इसकी आवश्यकता है। इसका उपयोग करने वाले उदाहरणों को अद्यतन किया जाना चाहिए।

बुनियादी घटक

निम्नलिखित HTML फ़ाइल को देखते हुए:

index.html

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8" />
    <title>React Tutorial</title>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.2.1/react.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.2.1/react-dom.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.34/browser.min.js"></script>
  </head>
  <body>
    <div id="content"></div>
    <script type="text/babel" src="scripts/example.js"></script>
  </body>
</html>

आप एक अलग फ़ाइल में निम्नलिखित कोड का उपयोग करके एक बुनियादी घटक बना सकते हैं:

लिपियों / example.js

import React, { Component } from 'react';
import ReactDOM from 'react-dom';

class FirstComponent extends Component {
  render() {
    return (
      <div className="firstComponent">
        Hello, world! I am a FirstComponent.
      </div>
    );
  }
}
ReactDOM.render(
  <FirstComponent />, // Note that this is the same as the variable you stored above
  document.getElementById('content')
);

आपको निम्न परिणाम मिलेगा (ध्यान दें कि div#content अंदर क्या है):

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8" />
    <title>React Tutorial</title>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.2.1/react.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.2.1/react-dom.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.34/browser.min.js"></script>
  </head>
  <body>
    <div id="content">
        <div className="firstComponent">
            Hello, world! I am a FirstComponent.
        </div>
    </div>
    <script type="text/babel" src="scripts/example.js"></script>
  </body>
</html>

घोंसले के शिकार घटक

ReactJS की बहुत अधिक शक्ति घटकों के घोंसले के शिकार की अनुमति देने की क्षमता है। निम्नलिखित दो घटक लें:

var React = require('react');
var createReactClass = require('create-react-class');

var CommentList = reactCreateClass({
  render: function() {
    return (
      <div className="commentList">
        Hello, world! I am a CommentList.
      </div>
    );
  }
});

var CommentForm = reactCreateClass({
  render: function() {
    return (
      <div className="commentForm">
        Hello, world! I am a CommentForm.
      </div>
    );
  }
});

आप एक अलग घटक की परिभाषा में उन घटकों को घोंसले और संदर्भित कर सकते हैं:

var React = require('react');
var createReactClass = require('create-react-class');

var CommentBox = reactCreateClass({
  render: function() {
    return (
      <div className="commentBox">
        <h1>Comments</h1>
        <CommentList /> // Which was defined above and can be reused
        <CommentForm /> // Same here
      </div>
    );
  }
});

इसके अलावा घोंसले के शिकार को तीन तरीकों से किया जा सकता है, जिसका उपयोग करने के लिए सभी के अपने स्थान हैं।

1. बच्चों का उपयोग किए बिना घोंसला बनाना

(ऊपर से जारी)

var CommentList = reactCreateClass({
  render: function() {
    return (
      <div className="commentList">
        <ListTitle/>
        Hello, world! I am a CommentList.
      </div>
    );
  }
});

यह वह शैली है जहाँ A, B और B से C बनाता है।

पेशेवरों

  • UI तत्वों को अलग करने के लिए आसान और तेज़
  • पैरेंट कंपोनेंट की स्थिति के आधार पर बच्चों को प्रॉपर इंजेक्शन देना आसान है

विपक्ष

  • रचना वास्तुकला में कम दृश्यता
  • कम पुन: प्रयोज्य

अगर अच्छा है

  • बी और सी सिर्फ प्रस्तुतिकरण घटक हैं
  • B, C के जीवनचक्र के लिए जिम्मेदार होना चाहिए

2. बच्चों का उपयोग करते हुए घोंसला बनाना

(ऊपर से जारी)

var CommentBox = reactCreateClass({
  render: function() {
    return (
      <div className="commentBox">
        <h1>Comments</h1>
        <CommentList>
            <ListTitle/> // child
        </CommentList>
        <CommentForm />
      </div>
    );
  }
});

यह वह शैली है जहाँ A, B की रचना करता है और A, B को C, मूल घटक की अधिक शक्ति की रचना करने के लिए कहता है।

पेशेवरों

  • बेहतर घटक जीवन चक्र प्रबंधन
  • रचना वास्तुकला में बेहतर दृश्यता
  • बेहतर पुन: प्रयोज्य

विपक्ष

  • प्रॉप्स को इंजेक्ट करना थोड़ा महंगा हो सकता है
  • बाल घटकों में कम लचीलापन और शक्ति

अगर अच्छा है

  • B को भविष्य में C से अलग या कहीं और रचना करने के लिए स्वीकार करना चाहिए
  • A को C के जीवनचक्र को नियंत्रित करना चाहिए

B, this.props.children का उपयोग करके C को रेंडर करेगा, और B के लिए संरचित तरीका नहीं है जिससे यह पता चल सके कि वे बच्चे कौन से हैं। तो, बी अतिरिक्त प्रॉप्स को कम करके बच्चे के घटकों को समृद्ध कर सकता है, लेकिन यदि बी को यह जानने की आवश्यकता है कि वे क्या हैं, # 3 एक बेहतर विकल्प हो सकता है।

3. प्रॉप्स का उपयोग करते हुए घोंसला बनाना

(ऊपर से जारी)

var CommentBox = reactCreateClass({
  render: function() {
    return (
      <div className="commentBox">
        <h1>Comments</h1>
        <CommentList title={ListTitle}/> //prop
        <CommentForm />
      </div>
    );
  }
});

यह वह शैली है जहाँ A, B और B की रचना करता है, A को एक विशिष्ट उद्देश्य के लिए रचना करने के लिए कुछ पास करने का विकल्प प्रदान करता है। अधिक संरचित रचना।

पेशेवरों

  • एक विशेषता के रूप में रचना
  • आसान सत्यापन
  • बेहतर सम्मोहन

विपक्ष

  • प्रॉप्स को इंजेक्ट करना थोड़ा महंगा हो सकता है
  • बाल घटकों में कम लचीलापन और शक्ति

अगर अच्छा है

  • B में कुछ बनाने के लिए परिभाषित विशिष्ट विशेषताएं हैं
  • B को केवल यह पता होना चाहिए कि रेंडर को कैसे रेंडर करना है

# 3 आम तौर पर घटकों के एक सार्वजनिक पुस्तकालय बनाने के लिए बहुत जरूरी है, लेकिन यह भी सामान्य रूप से एक अच्छा व्यवहार करने योग्य घटक बनाने के लिए और स्पष्ट रूप से संरचना सुविधाओं को परिभाषित करना चाहिए। # 1 कुछ काम करने के लिए सबसे आसान और सबसे तेज़ है, लेकिन # 2 और # 3 को विभिन्न उपयोग मामलों में कुछ लाभ प्रदान करना चाहिए।

अवयव बनाना

यह बेसिक उदाहरण का एक विस्तार है:

बुनियादी संरचना

import React, { Component } from 'react';
import { render } from 'react-dom';

class FirstComponent extends Component {
    render() {
        return (
            <div>
                Hello, {this.props.name}! I am a FirstComponent.
            </div>
        );
    }
}

render(
    <FirstComponent name={ 'User' } />,
    document.getElementById('content')
);

उपरोक्त उदाहरण को एक स्टेटलेस घटक कहा जाता है क्योंकि इसमें राज्य (शब्द के रिएक्ट अर्थ में) शामिल नहीं है।

ऐसे में कुछ लोगों को स्टेटलेस फंक्शनल कंपोनेंट्स का इस्तेमाल करना बेहतर लगता है, जो ईएस 6 एरो फंक्शन्स पर आधारित हैं।

स्टेटलेस फंक्शनल कंपोनेंट

कई अनुप्रयोगों में स्मार्ट घटक होते हैं जो राज्य को पकड़ते हैं लेकिन गूंगे घटकों को प्रस्तुत करते हैं जो बस सहारा प्राप्त करते हैं और HTML को JSX के रूप में वापस करते हैं। स्टेटलेस कार्यात्मक घटक बहुत अधिक पुन: प्रयोज्य हैं और आपके आवेदन पर सकारात्मक प्रदर्शन प्रभाव डालते हैं।

उनकी 2 मुख्य विशेषताएं हैं:

  1. जब उन्हें प्रदान किया जाता है तो वे उन सभी सहारा के साथ एक वस्तु प्राप्त करते हैं जो नीचे पारित किए गए थे
  2. उन्हें प्रदान किए जाने वाले JSX को वापस करना होगा
// When using JSX inside a module you must import React
import React from 'react';
import PropTypes from 'prop-types';

const FirstComponent = props => (
    <div>
        Hello, {props.name}! I am a FirstComponent.
    </div>
);

//arrow components also may have props validation
FirstComponent.propTypes = {
    name: PropTypes.string.isRequired,
}

// To use FirstComponent in another file it must be exposed through an export call:
export default FirstComponent;

स्टेटफुल घटक

ऊपर दिखाए गए 'स्टेटलेस' घटकों के विपरीत, 'स्टेटफुल' घटकों में एक राज्य ऑब्जेक्ट होता है जिसे setState विधि से अपडेट किया जा सकता है। सेट होने से पहले राज्य को constructor में आरंभीकृत किया जाना चाहिए:

import React, { Component } from 'react';

class SecondComponent extends Component {
    constructor(props) {
        super(props);

        this.state = {
            toggle: true
        };

        // This is to bind context when passing onClick as a callback
        this.onClick = this.onClick.bind(this);
    }

    onClick() {
        this.setState((prevState, props) => ({
            toggle: !prevState.toggle
        }));
    }
    
    render() {
        return (
            <div onClick={this.onClick}>
                Hello, {this.props.name}! I am a SecondComponent.
                <br />
                Toggle is: {this.state.toggle}
            </div>
        );
    }
}

के साथ एक घटक का विस्तार PureComponent के बजाय Component स्वचालित रूप से लागू करेगा shouldComponentUpdate() उथले प्रोप और राज्य तुलना के साथ जीवन चक्र विधि। यह आपके एप्लिकेशन को होने वाले अन-आवश्यक रेंडरर्स की मात्रा को कम करके अधिक निष्पादक रखता है। यह मानता है कि आपके घटक 'प्योर' हैं और हमेशा समान आउटपुट को उसी स्थिति और प्रॉपर इनपुट के साथ प्रस्तुत करते हैं।

उच्चतर आदेश घटक

उच्च क्रम के घटक (HOC) घटक कार्यक्षमता को साझा करने की अनुमति देते हैं।

import React, { Component } from 'react';

const PrintHello = ComposedComponent => class extends Component {
    onClick() {
        console.log('hello');
    }
    
    /* The higher order component takes another component as a parameter 
    and then renders it with additional props */
    render() {
        return <ComposedComponent {...this.props } onClick={this.onClick} />
    }
}

const FirstComponent = props => (
    <div onClick={ props.onClick }>
        Hello, {props.name}! I am a FirstComponent.
    </div>
);

const ExtendedComponent = PrintHello(FirstComponent);

जब आप कितने अलग-अलग तरीके से तर्क प्रस्तुत करना चाहते हैं तो उच्चतर स्तर के घटकों का उपयोग किया जाता है।

सेटटेस्ट नुकसान

अतुल्यकालिक संदर्भ में setState का उपयोग करते समय आपको सावधानी बरतनी चाहिए। उदाहरण के लिए, आप एक अनुरोध प्राप्त करने के कॉलबैक में setState को कॉल करने का प्रयास कर सकते हैं:

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

        this.state = {
            user: {}
        };
    }

    componentDidMount() {
        this.fetchUser();
    }

    fetchUser() {
        $.get('/api/users/self')
            .then((user) => {
                this.setState({user: user});
            });
    }

    render() {
        return <h1>{this.state.user}</h1>;
    }
}

यह समस्याओं को कॉल कर सकता है - यदि Component this.setState होने के बाद कॉलबैक कहा जाता है, तो यह ' this.setState फ़ंक्शन नहीं होगा। जब भी ऐसा होता है, तो आपको यह सुनिश्चित करने के लिए सावधान रहना चाहिए कि आपका setState का उपयोग रद्द हो।

इस उदाहरण में, आप घटक के छूटने पर XHR अनुरोध को रद्द करने की इच्छा कर सकते हैं:

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

        this.state = {
            user: {},
            xhr: null
        };
    }

    componentWillUnmount() {
        let xhr = this.state.xhr;

        // Cancel the xhr request, so the callback is never called
        if (xhr && xhr.readyState != 4) {
            xhr.abort();
        }
    }

    componentDidMount() {
        this.fetchUser();
    }

    fetchUser() {
        let xhr = $.get('/api/users/self')
            .then((user) => {
                this.setState({user: user});
            });

        this.setState({xhr: xhr});
    }
}

Async विधि को एक स्थिति के रूप में सहेजा जाता है। में componentWillUnmount एक्सएचआर अनुरोध रद्द करने सहित - आप अपने सभी सफाई प्रदर्शन करते हैं।

आप कुछ अधिक जटिल भी कर सकते हैं। इस उदाहरण में, मैं एक 'स्टेटसेट्टर' फ़ंक्शन बना रहा हूँ, जो इस ऑब्जेक्ट को एक तर्क के रूप में स्वीकार करता है और इस को रोकता है this.setState जब फ़ंक्शन cancel किया जाता है, तो इसे:

function stateSetter(context) {
    var cancelled = false;
    return {
        cancel: function () {
            cancelled = true;
        },
        setState(newState) {
            if (!cancelled) {
                context.setState(newState);
            }
        }
    }
}

class Component extends React.Component {
    constructor(props) {
        super(props);
        this.setter = stateSetter(this);
        this.state = {
            user: 'loading'
        };
    }
    componentWillUnmount() {
        this.setter.cancel();
    }
    componentDidMount() {
        this.fetchUser();
    }
    fetchUser() {
        $.get('/api/users/self')
            .then((user) => {
                this.setter.setState({user: user});
            });
    }
    render() {
        return <h1>{this.state.user}</h1>
    }
}

यह काम करता है क्योंकि cancelled किया cancelled वैरिएबल setState क्लोजर में दिखाई देता है setState हमने बनाया था।

रंगमंच की सामग्री

Props एक प्रतिक्रिया घटक में जानकारी को पारित करने का एक तरीका है, उनके पास किसी भी प्रकार के कार्य शामिल हो सकते हैं - कभी-कभी कॉलबैक के रूप में संदर्भित किया जाता है।

JSX प्रॉम्प्स में विशेषता सिंटैक्स के साथ पारित किया जाता है

<MyComponent userID={123} />

MyComponent userID के लिए परिभाषा के अंदर अब प्रॉपर ऑब्जेक्ट से एक्सेस किया जा सकेगा

// The render function inside MyComponent
render() {
    return (
        <span>The user's ID is {this.props.userID}</span>
    )
}

सभी props , उनके प्रकार और जहां लागू हो, उनके डिफ़ॉल्ट मान को परिभाषित करना महत्वपूर्ण है:

// defined at the bottom of MyComponent
MyComponent.propTypes = {
    someObject: React.PropTypes.object,
    userID: React.PropTypes.number.isRequired,
    title: React.PropTypes.string
};

MyComponent.defaultProps = {
    someObject: {},
    title: 'My Default Title'
}

इस उदाहरण में प्रोप someObject वैकल्पिक है, लेकिन प्रोप userID की आवश्यकता है। आप प्रदान करने में विफल रहते हैं userID को MyComponent , रनटाइम पर प्रतिक्रिया इंजन एक कंसोल आप चेतावनी देता है कि आवश्यक प्रोप प्रदान नहीं किया गया दिखाएगा। हालांकि सावधान रहें, यह चेतावनी केवल रिएक्ट लाइब्रेरी के विकास संस्करण में दिखाई गई है, उत्पादन संस्करण किसी भी चेतावनी को लॉग नहीं करेगा।

defaultProps का उपयोग करना आपको सरल बनाने की अनुमति देता है

const { title = 'My Default Title' } = this.props;
console.log(title);

सेवा

console.log(this.props.title);

यह object array और functions उपयोग के लिए एक सुरक्षा उपाय भी है। यदि आप किसी ऑब्जेक्ट के लिए डिफ़ॉल्ट प्रोप प्रदान नहीं करते हैं, तो निम्न त्रुटि पारित करेगा यदि प्रोप पास नहीं है:

if (this.props.someObject.someKey)

उपरोक्त उदाहरण में, this.props.someObject है undefined और इसलिए की जांच someKey एक त्रुटि फेंक देंगे और कोड टूट जाएगा। defaultProps के उपयोग से आप सुरक्षित रूप से उपरोक्त चेक का उपयोग कर सकते हैं।

घटक बताता है - डायनामिक उपयोगकर्ता-इंटरफ़ेस

मान लें कि हम निम्नलिखित व्यवहार करना चाहते हैं - हमारे पास एक शीर्षक है (h3 तत्व) और इसे क्लिक करने पर, हम चाहते हैं कि यह एक इनपुट बॉक्स बन जाए ताकि हम शीर्षक नाम को संशोधित कर सकें। प्रतिक्रिया यह अत्यधिक सरल और सहज ज्ञान युक्त घटक राज्यों और अगर बयानों का उपयोग करता है। (नीचे कोड स्पष्टीकरण)

// I have used ReactBootstrap elements. But the code works with regular html elements also
var Button = ReactBootstrap.Button;
var Form = ReactBootstrap.Form;
var FormGroup = ReactBootstrap.FormGroup;
var FormControl = ReactBootstrap.FormControl;

var Comment = reactCreateClass({
  getInitialState: function() {
    return {show: false, newTitle: ''};
  },

  handleTitleSubmit: function() {
     //code to handle input box submit - for example, issue an ajax request to change name in database
  },

  handleTitleChange: function(e) {
    //code to change the name in form input box. newTitle is initialized as empty string. We need to update it with the string currently entered by user in the form
    this.setState({newTitle: e.target.value});
  },

  changeComponent: function() {
    // this toggles the show variable which is used  for dynamic UI
    this.setState({show: !this.state.show)};
  },

  render: function() {

    var clickableTitle;

    if(this.state.show) {
        clickableTitle = <Form inline onSubmit={this.handleTitleSubmit}>
                             <FormGroup controlId="formInlineTitle">
                                 <FormControl type="text" onChange={this.handleTitleChange}>
                             </FormGroup>
                         </Form>;
    } else {
        clickabletitle = <div>
                            <Button bsStyle="link" onClick={this.changeComponent}>
                                <h3> Default Text </h3>
                            </Button>
                         </div>;
    }

    return (
        <div className="comment">
            {clickableTitle}
        </div>
    );
  }
});

ReactDOM.render(
    <Comment />, document.getElementById('content')
);

कोड का मुख्य भाग क्लिक करने योग्य तालिका चर है। राज्य चर शो के आधार पर, यह या तो एक फार्म तत्व या एक बटन तत्व हो सकता है। प्रतिक्रिया घटकों के घोंसले के शिकार की अनुमति देता है।

इसलिए हम रेंडर फंक्शन में {clickableTitle} एलिमेंट जोड़ सकते हैं। यह क्लिक करने योग्य तालिका चर के लिए दिखता है। 'This.state.show' मान के आधार पर, यह संबंधित तत्व प्रदर्शित करता है।

स्टेटलेस फंक्शनल कंपोनेंट्स के वेरिएशन

const languages = [
  'JavaScript',
  'Python',
  'Java',
  'Elm',
  'TypeScript',
  'C#',
  'F#'
]

// one liner
const Language = ({language}) => <li>{language}</li>

Language.propTypes = {
  message: React.PropTypes.string.isRequired
}

/**
* If there are more than one line.
* Please notice that round brackets are optional here,
* However it's better to use them for readability
*/
const LanguagesList = ({languages}) => {
  <ul>
    {languages.map(language => <Language language={language} />)}
  </ul>
}

LanguagesList.PropTypes = {
  languages: React.PropTypes.array.isRequired
}

/**
 * This syntax is used if there are more work beside just JSX presentation
 * For instance some data manipulations needs to be done.
 * Please notice that round brackets after return are required,
 * Otherwise return will return nothing (undefined)
 */
const LanguageSection = ({header, languages}) => {
  // do some work
  const formattedLanguages = languages.map(language => language.toUpperCase())
  return (
    <fieldset>
      <legend>{header}</legend>
      <LanguagesList languages={formattedLanguages} />
    </fieldset>
  )
}

LanguageSection.PropTypes = {
  header: React.PropTypes.string.isRequired,
  languages: React.PropTypes.array.isRequired
}

ReactDOM.render(
  <LanguageSection 
    header="Languages" 
    languages={languages} />,
  document.getElementById('app')
)

यहां आप इसका उदाहरण देख सकते हैं।



Modified text is an extract of the original Stack Overflow Documentation
के तहत लाइसेंस प्राप्त है CC BY-SA 3.0
से संबद्ध नहीं है Stack Overflow