如何在组件之间传递状态属性
Posted
技术标签:
【中文标题】如何在组件之间传递状态属性【英文标题】:How to pass state properties from component to component 【发布时间】:2021-09-13 10:40:50 【问题描述】:我目前正在学习 React,并且正在尝试创建一个基本的待办事项列表应用程序。我在理解如何在组件之间传递数据时遇到了问题。
我需要当我在我的主组件的模式中添加一个任务时,它会被添加到我的公共任务组件的“发布”状态中,以便渲染任务。
我加入了两个组件的代码,
希望有人可以帮助我:)
function PublicTask ()
const [pub,setPub] = useState([id: 1, value : "test",id: 2, value : "test2"]);
function ToDoPublicItem()
const pubT = pub.map(value =>
return(
<div className= 'pubTask-item'>
<li>value.value</li>
</div>
)
);
return(
<div>
<div>
pubT
</div>
</div>
);
return(
<div className= 'item-container'>
<h2 style=color:'white'>Public Tasks</h2>
<ToDoPublicItem/>
</div>
);
export default PublicTask;
function Home()
const [show,setShow] = useState(false);
const [pubTask,setPubTask] = useState([]);
function openModal()
setShow(true);
function Modal()
const[textTodo, setTextTodo] = useState('')
const addItem = () =>
const itemTopush = textTodo;
pubTask.push(itemTopush);
return(
<div className='modal'>
<div className = 'modal-title'>
<h2>ADD A TODO</h2>
<hr></hr>
</div>
<div className= 'modal-body'>
<input type='text' onChange = (e) => setTextTodo(e.target.value)/>
<input type="checkbox" id="pub" value ='public'/>
<label htmlfor="pub">Public</label>
<input type="checkbox" id="priv" value= 'private '/>
<label Htmlfor="riv">Private</label>
<hr></hr>
<Button id='button-add' size='large' style=backgroundColor : 'white' onClick=()=> addItem()>ADD</Button>
<hr></hr>
<Button id='button-close' size='large' style=backgroundColor : '#af4c4c' onClick= ()=> setShow(false) >CLOSE</Button>
</div>
</div>
)
return(
<div>
<h1 style=textAlign:'center'>You are logged in !</h1>
<div>
<button id='button-logout' onClick = () => firebaseApp.auth().signOut()>Logout</button>
</div>
<div>
<Fab color="primary" aria-label="add" size = 'large' onClick = () => openModal()>
<Add/>
</Fab>
show ? <Modal/> : <div></div>
</div>
<div>
<Router>
<div className='pub-container'>
<Link to='/publicTasks'>Public Tasks </Link>
</div>
<div className='ongo-container'>
<Link to='/onGoingTasks'>On Going Tasks </Link>
</div>
<div className='finish-container'>
<Link to='/finishedTasks'>Finished Tasks </Link>
</div>
<Route path='/publicTasks' component = PublicTask/>
<Route path='/onGoingTasks' component = OngoingTask/>
<Route path='/finishedTasks' component = FinishedTask/>
</Router>
</div>
</div>
);
export default Home;
【问题讨论】:
(当呈现一段连续的预先格式化的东西时,比如源代码,使用代码块。我发现将它包含在只包含~~~
的行中最不麻烦。)
【参考方案1】:
您可以像这样在 React 组件之间共享数据:
const [value, setValue] = useState("test"); // data that you want to share
return (
<Parent data=value> // pass data to parent in your child component
);
<h1>this.props.data</h1> // do something with the data in the parent component
【讨论】:
以上是关于如何在组件之间传递状态属性的主要内容,如果未能解决你的问题,请参考以下文章