我有一个带有条件渲染的组件:'如果组件具有道具“showCross”,则显示一个带有十字的按钮,除非什么都没有'。一切正常,当有 showCross 时,就有十字架,除非什么都没有:
import PropTypes from 'prop-types'
import React from 'react'
import {Cell} from 'react-mdl/lib/Grid'
class RefundFormContent extends React.Component {
render() {
const { fields, onClose } = this.props
const style = {width: '150px'}
function CrossButton(props) {
let {showCross} = props
const displayCross =
showCross ? <button
className="mdl-button mdl-js-button mdl-button--icon"
onClick={onClose}
>x</button>
: null
return (
<div>{displayCross}</div>
)
}
return (
<React.Fragment>
<Cell col={3}>
<Formfield {...fields.type} style={style} />
</Cell>
<Cell col={4}>
<Formfield {...fields.provider} style={style} />
</Cell>
<Cell col={4}>
<Formfield {...fields.amount} style={style} />
</Cell>
<Cell col={1} className="mdl-typography--text-right">
<CrossButton showCross />
</Cell>
</React.Fragment>
)
}
}
export default RefundFormContent
但问题是当我在另一个组件中使用这个组件时,即使 prop 被传递给 false,十字仍然显示(我想隐藏它):
import PropTypes from 'prop-types'
import React from 'react'
import Grid from 'react-mdl/lib/Grid'
import Form from 'forms/Form'
import {validateCurrency} from 'forms/inputs/currency'
import {makeChoices} from 'forms/utils'
import RefundFormContent from './RefundFormContent'
const RefundForm = (
{values=null, types, providers, onClose, showCross=false}
) => {
const fields = {
type: {
label: 'Type',
choices: makeChoices(types),
floatingLabel: true,
},
provider: {
label: 'Demandeur',
choices: makeChoices(providers),
floatingLabel: true,
},
amount: {
label: 'Montant',
validators: [validateCurrency],
floatingLabel: true,
placeholder: 'euros',
},
comment: {
label: 'Commentaire',
required: false,
floatingLabel: true,
},
}
return (
<Grid style={{backgroundColor: '#EEE', boxShadow: '1px 1px 5px 0 #A9A',
margin: '20px 0'}}>
<Form
component={RefundFormContent}
componentProps={{onClose}}
fields={fields}
showCross={false}
/>
</Grid>
)
}
export default RefundForm
控制台没有错误,只是没有按预期显示。通过 React 开发者工具我可以看到 props 和预期一样为 false,但是显示不符合显示条件(即:'display nothing')。最重要的是故事书,但我不确定这与显示问题有关:
import React from 'react'
import { storiesOf } from '@storybook/react'
import RefundAssignment from '../account/RefundAssignment'
storiesOf('RefundAssignment', module)
.add('Affectation', () =>
<RefundAssignment
types={['1', '2', '3']}
providers={['Deborah', 'Patrick', 'Severine',
'Patrick Swayze']}
showCross={false}
/>
)