![](/img/trans.png)
[英]Changing the state of one component from another component in React-native
[英]Issue with Changing state from 1 React Component inside of another React component
我一直在尝试更改在 medCardSong.js 文件中创建的“ModalOn”状态,并且我一直在尝试从“SongModal.js”文件中更改该状态,该文件是内部的子组件medCardSong.js 的。
我已经输入了 changeState 函数“SetModalOn”作为 SongModal.js 组件的道具,并且我尝试通过它来改变状态。
这是 medCardSong.js:
import React, { useEffect } from 'react';
import { useState} from 'react';
import SongModal from '../modals/SongModal';
function MediumCardSong(props) {
const [ModalOn, SetModalOn] = useState(false);
function killme() {
SetModalOn(false);
console.log(7)
}
console.log(ModalOn)
return (
<div className={" flex flex-col m-2 overflow-hidden duration-300 w-52 " + (ModalOn
? 'transition-none' : 'hover:scale-105 transition-all')} onClick={() =>
{SetModalOn(true);}}>
<img className='object-cover rounded-3xl'
src="https://i0.wp.com/coolhunting.com/wp-content/uploads/2022/07/steve-lacy-
bad-habit.jpg?fit=586%2C586&ssl=1" alt="" />
<div className='pb-2'>
<div className='flex'>
<div className='px-2 pt-2 text-2xl font-bold text-gray-400'>#1</div>
<div className='pl-3 text-xl pt-2 text-white'>Mercury</div>
</div>
<div className='text-left pl-5 text-gray-500'>Steve Lacy</div>
</div>
{ModalOn && <SongModal CloseModal={killme} />}
</div>
);
}
export default MediumCardSong;
这是 SongModal.js:
从“反应”导入反应
function SongModal(props) {
// setTimeout(() => {props.CloseModal(false)}, 1000)
return (
<div className="bg-neutral-800 bg-opacity-60 fixed inset-0 z-50 backdrop-blur-sm">
<div className="flex h-screen justify-center items-center">
<div className="justify-center bg-neutral-700 py-12 px-24 border-4 border-
pearmint rounded-xl text-xl text-white" >
<button className='text-3xl text-white pr-24 pb-24'
onClick={() => {props.CloseModal()}} >X</button>
sad
</div>
</div>
</div>
)
};
导出默认 SongModal;
导入的 CloseModal 函数在 jsx 之外应用时按预期工作。 例如,如果未注释,“SetTimeOut”代码段将正常工作。 但是,当我在 Onclick 事件处理程序中调用“CloseModal”时,这不会发生,例如我为“x”按钮所做的调用。
我还使用了 console.log 来查看按钮是否已经注册了我所做的点击,并且确实如此。 所以我很困惑为什么 props.CloseModal 函数在 OnClick 事件侦听器中不能按预期工作。 可以的话请给点建议。
尝试在钩子内调用它
function SongModal(props) { const close = () => { props.CloseModal() } return ( <div> <button onClick={close}>Close Btn</button> </div> ) };
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.