I am actually learning how to design React components, and I need to create a DefaultProp for a property on it. This is my code:
import React from 'react'
import PropTypes from 'prop-types'
class Component extends React.Component{
constructor(props){
super(props)
}
render(){
return(
<li className="nav-item">
<a className="nav-link" href={this.props.element.value1}>{this.props.element.value2}</a>
</li>
)
}
}
Component.defaultProps = { // does not set the default value when value1 is not passed
element: {value1: '#', value2: 'foo'}
}
export default Component
As my property element
has two properties ( value1
and value2
) I find myself unable to refer to it before accesing its properties and set the default value.
I've also tried these variations, resulting all of them on an error:
Component.defaultProps = {
element.value1: '#'
}
Component.defaultProps = {
this.props.element.value1: '#'
}
Since the propType
of element
is shape
with value1
and value2
properties you need to set an object as default value with those properties:
Component.defaultProps = {
element: {value1: '#', value2: 'foo'}
}
Note that the default value is only used if you don't give any element
prop to the component, ie
<Component element={{value1: '#'}}/>
will not add the value2
prop for you. If that's what you want, you need to do it yourself:
render(){
const value2 = this.props.element.value2 || 'default-value'
return(
<li className="nav-item">
<a className="nav-link" href={this.props.element.value1}>{value2}</a>
</li>
)
}
And then you shouldn't specify value2
as isRequired
.
You could use ES6 default arguaments
. It is worth reading about them here it states:
In JavaScript, function parameters default to undefined. However, it's often useful to set a different default value. This is where default parameters can help.
An example to help explain is the following
function getInfo (name, year = 2018, color = 'blue') {
console.log(name, year, color);
}
getInfo('Chevy', 1957, 'Green'); // result --> "Chevy" 1957 "Green"
getInfo('Benz', 1975); // result --> "Benz" 1975 "blue"
getInfo('Honda'); // result --> "Honda" 2018 "blue"
I would recommend something like the following.
render() {
const {
value1 = 'defaultValue1',
value2 = 'defaultValue2'
} = this.props;
return(
<li className="nav-item">
<a className="nav-link" href={value1}>{value2}</a>
</li>
)
}
If value1
or value2
props are undefined then it will default to the value you enter.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.