I see in some source code, the author wrote a component like this:
import React from 'react';
export const Login = () => (
<div>
<h4>Hello World</h4>
</div>
);
export default Login;
The thing I don't know is:
viewDidMount
... I have added in code block but it compiles fail.thanks
If you want to write a component that takes advantage of the lifecycle methods you will need to extend the default Component class. The Component class contains the lifecycle methods and should not be confused with other generic react components, such as functional components or any component you may write.
Yes, React class components will fade away in the future. If you want to embrace modern React, then you should use function components with hooks. That's why you will find most tutorials out there teaching modern React and no class components anymore.
Whenever a class component is created, it is necessary to extend the component, however, if a functional component is created, it is not necessary to extend the component. With functional components, we can use props directly.
You can pass a component as props in React by using the built-in children prop. All elements you pass between the opening and closing tags of a component get assigned to the children prop.
This is functional stateless component. It is for simple components.
You also can add component property types like this:
export const Login = () => (
<div>
<h4>Hello World</h4>
</div>
);
Login.propTypes = {
username: React.PropTypes.string.isRequired,
}
You can add callback like this:
// this place to define callback is more effective
const onClick = e => (...)
const Login = props => {
// or define here if you need access to props in onClick
const onClick = e => (...)
return <button onClick={onClick}>Submit</button>
}
React "knows" that the code you wrote is a React Component because of transpilation. Transpilation is a process that occurs during build time where your code is changed from the code you wrote into something else.
In the case of React and JSX, your code turns into
export const Login = () => (
React.createElement('div', {},
React.createElement('h4', {}, 'Hello World')
);
);
The angle brackets (<
) are syntactic sugar for React.createElement
and people use the angle brackets because they are simpler to use and type.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With