英文:
how to have react wait until load with react / jsx for styling?
问题
I'm consistently having this issue where with js/jsx/react, i am consistently running into this issue where my logic is running before the page loads, and because of that, i am consistently running into errors and what not as my code trys to execute before my page has finished loading resulting in a tonne of errors.
我一直遇到的问题是,在使用JavaScript/JSX/React时,我的逻辑经常在页面加载之前运行,因此我一直遇到错误和其他问题,因为我的代码尝试在页面完成加载之前执行,从而导致大量错误。
How do I consistently prevent this/prevent myself from running into these issues?
如何才能始终防止这种情况发生,或者如何防止自己遇到这些问题?
I've tried using a bunch of window.onload() functions but that feels wrong and I feel like there should be a better way to do so that I'm unable to find with googling or on forums.
我尝试过使用一堆window.onload()函数,但感觉不对,我觉得应该有更好的方法来解决这个问题,但我在搜索或论坛上找不到答案。
The error I'm commonly getting is that React is claiming that the style I'm trying to change/access in JSX claims "do not exist," but if I try to change it in the console in the browser, it works fine.
我经常遇到的错误是React声称我尝试在JSX中更改/访问的样式“不存在”,但如果我尝试在浏览器的控制台中更改它,它可以正常工作。
英文:
i'm consistently having this issue where with js/jsx/react, i am consistently running into this issue where my logic is running before the page loads, and because of that, i am consistently running into errors and what not as my code trys to execute before my page has finished loading resulting in a tonne of errors.
how do i consistently prevent this/prevent myself from running into these issues?
i've tried using a bunch of window.onload() functions but that feels wrong and i feel like there should be a better way to do so that' i'm unable to find with googling or on forms.
// an example of my issue is the following code consistently errors:
function Title() {
var text = "Hello";
var arr = [];
//convert word into an array of chars
for (let i=0; i<=text.length; i++){
console.log("loop")
arr.push(text.charAt(i));
}
//output each letter into a span
const listItems = arr.map((number) => <span>{number}</span>);
//neither of these work
// document.getElementById('title').style.color = ('rgba(0, 0, 0, 0.0)');
// document.getElementById('title').style.color = "#ffFFff"
return (
<h1 id='title'>{listItems}</h1>
)
}
the error i'm commonly getting is that react is claiming that the style i'm trying to change/access jsx claims "do not exists", but if i try change it in the console in the browser, it works fine.
答案1
得分: 1
要向React元素添加内联样式,应该使用style
属性。这样做:
<h1 id="title" style={{ color: "#fff" }}>{listItems}</h1>
无法访问组件主体上呈现的DOM元素,您应该使用引用(ref)和useEffect
来实现此目的。
英文:
To add inline styles to a react element you should use the style prop. This way:
<h1 id="title" style={{ color: "#fff" }}>{listItems}</h1>
You can't get access to the DOM element which is being rendered on the body of the component, you should instead use a ref and an useEffect
for that purpose.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论