JSX打印文本有条件的财产没有风格的分量值
问题描述:
我有这个组件:JSX打印文本有条件的财产没有风格的分量值
<Button type="submit" { invalid ? 'primary': null }>
此组件样式的组件:
import styled from 'styled-components';
export const Button = styled.button`
font-size: 15px;
padding: 0.25em 1em;
border: solid 1px ${(props) => {
let color;
if (props.primary) {
color = 'red';
} else {
color = '#ffffff';
}
return color;
}};
`;
我得到这个错误:
Syntax error: Unexpected token ^invalid, expected ... (64:54)
我只需要发送属性'主'如果无效是真实的,得到这个:
<Button type="submit" primary/>
我不想写:
primary = { invalid }
的组件调用这个按钮是:
import React from 'react';
import { Button } from './layouts/cssstyled';
const getConditionalProps = (props) => {
// fill your `invalid` variable in this function or pass it to it
const myprops = {};
myprops.primary = true ;
myprops.secondary = false;
return myprops;
}
const Form = (props) => {
console.log('form props');
console.log(props);
const { handleSubmit, invalid, pristine, reset, submitting, t } = props;
return (
<form onSubmit={handleSubmit}>
<p>Invalid? {JSON.stringify(invalid)}</p>
<Button type="submit" disabled={submitting} primary={invalid ? "" : null} >
Buton styled component does not work
</Button>
<button primary={invalid ? "" : null}> button native works</button>
<div className="formError">
{pristine}
{invalid && t('form.haserrors')}
</div>
</div>
</form>
);
};
export default reduxForm({
form: 'CustomerForm', // a unique identifier for this form
})(Form);
答
我建议使用React-JS Spread Attributes。这是伟大的工具来传播与条件行为的组件上的道具:
class MyComponent extends React.Component {
// ...
getConditionalProps() {
const props = {};
// fill your `invalid` variable in this function or pass it to it
if (invalid) {
props.primary = true;
}
return props
}
render() {
return (
<Button type="submit"
{ ...this.getConditionalProps() } />
);
}
}
另一种解决方案是有条件的渲染:
class MyComponent extends React.Component {
// ...
render() {
return (invalid ?
<Button type="submit" primary />
:
<Button type="submit" />
);
}
}
请注意,有可能是一个更好的解决您的问题:你需要从组件本身内部处理组件Button
的行为,而不是试图从父组件决定是否发送特定的道具。但上述解决方案完全符合您的要求。
正确的方法肯定会让你写'primary = {invalid}'。有什么理由不写吗? – ZekeDroid
我使用一个只需要'主要'的CSS库,但为什么我不能在jsx中打印文本的技术原因? – DDave
@Dave由于react不是一个打印库,它是一个呈现为HTML的虚拟DOM。 – Sulthan