编程知识 cdmana.com

React learning notes props

React Is one for building user interfaces JAVASCRIPT library .React Mainly for building UI, Many people think that React yes MVC Medium V( View ).React Come of Facebook Internal projects , Used to set up Instagram Website , And in 2013 year 5 In open source .React High performance , The code logic is very simple , More and more people have begun to pay attention to and use it .

React Learning notes -PropsReact Learning notes -Props
state and props The main difference is this props It's immutable , and state It can be changed according to the interaction with users . That's why some container components need to be defined state To update and modify data . And subcomponents can only pass through props To transfer data .

Use Props

The following example demonstrates how to use it in a component props:

React example

function HelloMessage(props) {
    return <h1>Hello {props.name}!</h1>;
}
 
const element = <HelloMessage name="Runoob"/>;
 
ReactDOM.render(
    element,
    document.getElementById('example')
);

In the example name Property through props.name To get .

Default Props

You can use the component class defaultProps The attribute is props Set the default value , Examples are as follows :

React example

class HelloMessage extends React.Component {
  render() {
    return (
      <h1>Hello, {this.props.name}</h1>
    );
  }
}
 
HelloMessage.defaultProps = {
  name: 'Runoob'
};
 
const element = <HelloMessage/>;
 
ReactDOM.render(
  element,
  document.getElementById('example')
);
State and Props

The following example demonstrates how to combine state and props . We can set... In the parent component state, And by using props Pass it on to the subcomponents . stay render Function , We set up name and site To get the data passed by the parent component .

React example

class WebSite extends React.Component {
  constructor() {
      super();
 
      this.state = {
        name: "Linux It's time to learn ",
        site: "https://www.linuxprobe.com"
      }
    }
  render() {
    return (
      <div>
        <Name name={this.state.name} />
        <Link site={this.state.site} />
      </div>
    );
  }
}
 
 
 
class Name extends React.Component {
  render() {
    return (
      <h1>{this.props.name}</h1>
    );
  }
}
 
class Link extends React.Component {
  render() {
    return (
      <a href={this.props.site}>
        {this.props.site}
      </a>
    );
  }
}
 
ReactDOM.render(
  <WebSite />,
  document.getElementById('example')
);
Props verification

React.PropTypes stay React v15.5 The version has been moved to prop-types library .

<script src="https://cdn.bootcss.com/prop-types/15.6.1/prop-types.js"></script>

Props Verify use propTypes, It can ensure that our application components are used correctly ,React.PropTypes There are a lot of validators (validator) To verify that the incoming data is valid . Direction props When invalid data is passed in ,JavaScript The console will throw a warning .

The following example creates a Mytitle Components , attribute title Is required and is a string , Non string types are automatically converted to strings :

React 16.4 example

var title = "Linux It's time to learn ";
// var title = 123;
class MyTitle extends React.Component {
  render() {
    return (
      <h1>Hello, {this.props.title}</h1>
    );
  }
}
 
MyTitle.propTypes = {
  title: PropTypes.string
};
ReactDOM.render(
    <MyTitle title={title} />,
    document.getElementById('example')
);


React 15.4  example 
var title = "Linux It's time to learn ";
// var title = 123;
var MyTitle = React.createClass({
  propTypes: {
    title: React.PropTypes.string.isRequired,
  },
 
  render: function() {
     return <h1> {this.props.title} </h1>;
   }
});
ReactDOM.render(
    <MyTitle title={title} />,
    document.getElementById('example')
);

More verifiers are described below :

MyComponent.propTypes = {
    //  It can be stated that  prop  For the specified  JS  Basic data type , By default , These data are optional 
   optionalArray: React.PropTypes.array,
    optionalBool: React.PropTypes.bool,
    optionalFunc: React.PropTypes.func,
    optionalNumber: React.PropTypes.number,
    optionalObject: React.PropTypes.object,
    optionalString: React.PropTypes.string,
 
    //  Objects that can be rendered  numbers, strings, elements  or  array
    optionalNode: React.PropTypes.node,
 
    //  React  Elements 
    optionalElement: React.PropTypes.element,
 
    //  use  JS  Of  instanceof  Operator declaration  prop  Is an instance of a class .
    optionalMessage: React.PropTypes.instanceOf(Message),
 
    //  use  enum  To limit  prop  Only the specified value is accepted .
    optionalEnum: React.PropTypes.oneOf(['News', 'Photos']),
 
    //  It can be one of several object types 
    optionalUnion: React.PropTypes.oneOfType([
      React.PropTypes.string,
      React.PropTypes.number,
      React.PropTypes.instanceOf(Message)
    ]),
 
    //  Specifies an array of types 
    optionalArrayOf: React.PropTypes.arrayOf(React.PropTypes.number),
 
    //  Specifies the type of an object that consists of properties 
    optionalObjectOf: React.PropTypes.objectOf(React.PropTypes.number),
 
    //  given  shape  Object of parameter 
    optionalObjectWithShape: React.PropTypes.shape({
      color: React.PropTypes.string,
      fontSize: React.PropTypes.number
    }),
 
    //  Any type plus  `isRequired`  To make  prop  Do not empty .
    requiredFunc: React.PropTypes.func.isRequired,
 
    //  Any type that is not null 
    requiredAny: React.PropTypes.any.isRequired,
 
    //  Custom validator . Return one if the validation fails  Error  object . Don't use... Directly  `console.warn`  Or throw exceptions , Because of this  `oneOfType`  It will fail .
    customProp: function(props, propName, componentName) {
      if (!/matchme/.test(props[propName])) {
        return new Error('Validation failed!');
      }
    }
  }
}

 

 

This paper addresses :https://www.linuxprobe.com/react-study-props.html

版权声明
本文为[That's how Linux should learn]所创,转载请带上原文链接,感谢
https://cdmana.com/2020/12/20201225134628292R.html

Scroll to Top