Material UI - 将图标作为props传递

IT技术 javascript reactjs material-ui
2022-07-20 02:07:20

我正在尝试通过 prop 将 material-ui 图标插入到我的组件中。请让我知道我做错了什么。但是,我不确定如何在 JSX 中传递图标,这是我的非工作尝试:

这个片段是我试图将图标作为props传递给 Category 组件:

<Category icon="InboxOutlinedIcon" title="Tomorrow" categoryName="tomorrow" todos= 
{tomorrowTodos} toggleComplete={this.toggleComplete} handleDeleteTodo= 
{this.handleDeleteTodo}/>

组件类:

const Category = ({ title, icon, categoryName, todos, toggleComplete, handleDeleteTodo }) => (
    <div className="td-section">
        <div className="td-category">
            {/* Add Icon here */ }
            <div>{icon}</div>
            <h2 className={categoryName}>{title}</h2>
            
            <p className="td-count">{todos.length} todos</p>
        </div>
        <div className="td-list">
                {todos.map(todo => (
                        <Todo 
                            key={todo.id} 
                            toggleComplete={() => toggleComplete(todo.id)} 
                            onDelete={() => handleDeleteTodo(todo.id)}
                            todo={todo}
                        />
                ))}
        </div>
    </div>
)
export default Category
1个回答

将图标作为组件而不是字符串传递,因为 materai-ui 图标是现成的图标组件:

import InboxOutlinedIcon from 'materai-ui/...';    

<Category icon={<InboxOutlinedIcon />} .../>

在 Category 组件中使用如下:

const Category = ({ title, icon, categoryName, todos, toggleComplete, handleDeleteTodo }) => (
<div className="td-section">
    <div className="td-category">
        {icon}
        <div>{icon}</div>
        <h2 className={categoryName}>{title}</h2>
        
        <p className="td-count">{todos.length} todos</p>
    </div>
    <div className="td-list">
            {todos.map(todo => (
                    <Todo 
                        key={todo.id} 
                        toggleComplete={() => toggleComplete(todo.id)} 
                        onDelete={() => handleDeleteTodo(todo.id)}
                        todo={todo}
                    />
            ))}
    </div>
</div>
)
export default Category