我的目标是创建一个包含函数的组件,其中一个按钮删除一个包含文本的单独的div,该文本在React.js中由另一个div中的另一个组件呈现。
以下是我的app.js的代码。我想使用“ TurnOff”组件将“ tweetSection”的样式设置为“ none”(包含提供文本的Tweet组件)。
import logo from './logo.svg';
import Tweet from './Tweet';
import TurnOff from './TurnOff';
function App() {
return (
<div>
<div id="tweetSection">
<Tweet />
</div>
<div id="button">
<TurnOff />
</div>
</div>
);
}
export default App;```
这是我的TurnOff组件的代码
import React from 'react';
function TurnOff(){
const toggle = () => {
document.getElementById('tweetSection').style.display = "none";
}
return(
<div>
<button onClick={toggle()}>this is a button</button>
</div>
);
}
export default TurnOff;
运行此命令时,出现类型错误,指出“ TypeError:无法读取null的属性'style'。是否有一种简单的方法,或以其他方式对此进行编程以隐藏“ tweetSection” div?
一些东西。
要回答为什么会出现错误,这是因为您toggle()
用紧迫地调用了函数()onClick={toggle()}
。
使用此方法可以避免过早调用函数的问题:
<button onClick={toggle}>this is a button</button>
要么:
<button onClick={() => toggle()}>this is a button</button>
渲染后立即调用它,这意味着document.getElementById('tweetSection')
可能为null。
您可以像这样检查:
const el = document.getElementById('tweetSection');
if (el) {
el.style.display = "none";
} else {
console.warn('No tweetSection element found');
}
但是,解决此问题的更有效的方法是传递道具:
import logo from './logo.svg';
import Tweet from './Tweet';
import TurnOff from './TurnOff';
import React, {useState} from 'react';
function App() {
const [showTweet, setShowTweet] = useState(true);
return (
<div>
{showTweet && <div id="tweetSection">
<Tweet />
</div>}
<div id="button">
<TurnOff toggle={() => {
setShowTweet(!showTweet);
}}
/>
</div>
</div>
);
}
export default App;
import React from 'react';
function TurnOff({ toggle }){
return(
<div>
<button onClick={toggle}>this is a button</button>
</div>
);
}
export default TurnOff;
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句