我已经为我的应用程序设计了一个过滤器组件,该组件允许用户从下拉列表中选择要过滤的项目列表的方法。下拉选项的范围为文本,日期和下拉列表,仅显示所选的过滤方法。
我有一个JSX表达式,使我可以基于filter方法在各种组件之间交换。 text
和date
选项可以正常工作,但是dropdown
过滤器方法在JSX表达式(和其中的only)内损坏。这是称为优先级的下拉过滤器选项的代码:
<select value={priority} onChange={onChange} name="priority">
<option value="" disabled>
Filter...
</option>
<option value="low">by Low Priority</option>
<option value="norm">by Normal Priority</option>
<option value="high">by High Priority</option>
</select>
<label htmlFor="priority">Filtering by Priority Level</label>
条件格式遵循此格式:
{ filterType === 'name' ? (
// Name filter input code
) : filterType === 'date' ? (
// Date filter input code
) : filterType === 'priority' ? (
<Fragment>
<select value={priority} onChange={onChange} name="priority">
<option value="" disabled>
Filter...
</option>
<option value="low">by Low Priority</option>
<option value="norm">by Normal Priority</option>
<option value="high">by High Priority</option>
</select>
<label htmlFor="priority">Filtering by Priority Level</label>
</Fragment>
) : filterType === 'location' && (
// Location filter input code
)}
同样,代码的dropdown
代码段在JSX表达式外部也可以正常工作,但是在添加到上面的JSX表达式中时会中断。
编辑:忘记包括JSX表达式所需的Fragment
父元素。包含父元素的问题仍然存在。
我在下面的代码段中看不到该行为。
如果缺少任何细节会导致您的问题,请告诉我。但实际上,它似乎正在工作。
const {useState} = React;
const types = ['name', 'date', 'priority', ''];
const Example = () => {
const [value, setValue] = useState('');
const [filterType, setType] = useState('');
const onChange = (e) => setValue(e.target.value)
const toggleType = () => {
const lastIndex = types.indexOf(filterType) == types.length - 1 ? -1 : types.indexOf(filterType);
setType(types[lastIndex + 1])
}
return (
<div>
<div>
<button onClick={toggleType}>Toggle</button>
</div>
{ filterType === 'name' ? (
<div>Name</div>
) : filterType === 'date' ? (
<div>Date</div>
) : filterType === 'priority' ? (
<React.Fragment>
<select value={value} onChange={onChange} name="priority">
<option value="" disabled>
Filter...
</option>
<option value="low">by Low Priority</option>
<option value="norm">by Normal Priority</option>
<option value="high">by High Priority</option>
</select>
<label htmlFor="priority">Filtering by Priority Level</label>
</React.Fragment>
) :
<div>Else</div>
}
</div>
);
}
ReactDOM.render(<Example />, document.getElementById('root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script>
<div id="root"></div>