나는 버튼이 텍스트를 포함하는 별도의 div를 제거하는 함수를 포함하는 구성 요소를 만드는 것을 목표로하고 있습니다. 텍스트가 포함 된 별도의 div는 별도의 div의 다른 구성 요소에 의해 React.js에 표시됩니다.
아래는 내 app.js의 코드입니다. "TurnOff"구성 요소를 사용하여 "tweetSection"의 스타일을 "none"(텍스트를 제공하는 트윗 구성 요소 포함)으로 설정하고 싶습니다.
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 : Cannot read property 'style'of null"이라는 유형 오류가 발생합니다. 단순한 방법이 있습니까, 아니면 "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');
}
그러나이 문제를 해결하는 더 반응적인 방법은 props를 전달하는 것입니다.
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] 삭제
몇 마디 만하겠습니다