component
Components, conceptually similar to JavaScript functions. It takes an arbitrary input parameter (” props “) and returns a React element that describes what the page displays.
Function components and class components
Function components (JS functions)
// The function component is the js function, which takes the props argument and returns the react object
function Welcome(props) {
return <h1>Hello, {props.name}</h1>;
}
Copy the code
ES6 class components
class Welcome extends React.Component {
render() {
return <h1>Hello, {this.props.name}</h1>; }}Copy the code
Rendering component
React elements can also be user-defined components
const element = <Welcome name="Sara" />;
Copy the code
When the React element is a user-defined component, it converts attributes and children received by JSX into a single object passed to the component, which is called “props.”
// Declare the function component, accept the props argument and return the react object
function Topnav(props){
return <h1>this is {props.name}</h1>
}
const element= <Topnav name='navigation' />
ReactDOM.render(
element,
document.getElementById('root'))// pass
to reactdom.render ()
// React calls the Topnav component, passing name= navigation as props
// The TopNav component returns this is navigation as the return value;
// The page DOM is updated to this is navigation
// The component name must begin with a capital letter
Copy the code
Combination of components
Create a List component that renders multiple components
function Name(props) {
return <h1>Name: {props. The name}</h1>;
}
function Age(props) {
return <h1>Age: {props. Age}</h1>;
}
function Sex(props) {
return <h1>Gender: {props. Sex}</h1>;
}
function List() {
return (
<div>
<Name name="Zhang" />
<Age age="20" />
<Sex sex="Male" />
</div>
);
}
ReactDOM.render(
<List />.document.getElementById('root'));Copy the code