Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
381 views
in Technique[技术] by (71.8m points)

javascript - Change document.getElementsByClassName("parent")[0].children in React

I have a code in vanilla JS (javascript). I searched a lot of tutorial documents and videos for changing this code to React.

Following is the code in simple javascript

const Children = document.getElementsByClassName("parent")[0].children;
Array.from(sliderChildren).forEach((child) => {    
  });

Can anyone please help me how do this in react?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Generally, you just would not use DOM methods like getElementsByClassName in React.

By design, React doesn't "know" about the DOM elements at all, it only knows about its state, then renders the DOM elements from the state, and then "forgets" about the DOM elements again.

You may think this way:
you do not develop vanilla JS and HTML anymore, instead you develop React.

Anyway, if you really need it for some reason, you need to find a way to "manually" tell react that the DOM node is ready to be accessed. There is no way to "automatically" make React aware of the current state of DOM elements.

Note that you can not use something like window.onload for that, because that again is a methond from the DOM world as well.

e.g.:

export const SomeList = (props)=>{
    const list = [1,2,3,4,5,6];
    return (<div className="someParent">
        { list.map((item)=> <p className="someChildren">number { item }</p>) }
    </div>);
};

export const AccessDom = (props)=>{

    const accessDomNodes = function(){
        const Children = document.getElementsByClassName("someParent")[0].children;
        console.log('Children:', Children);
    };

    return (<div>
        <SomeList />
        <button type="button" onClick={ accessDomNodes }>
            I'm sure the DOM node exists now
        </button>
    </div>);
};

If you want to do something with the DOM elements in React, you need to pass it over into the React world by setting some React state:

export const AccessDom = (props)=>{
    const [ childsList, setChildsList ] = useState([]); // <-- a React state

    const accessDomNodes = function(){
        const Children = document.getElementsByClassName("someParent")[0].children;
        setChildsList( Array.from( Children ) );  // <-- set a React state
        console.log('Children:', Children);
    };

    return (<div>
        <SomeList />
        <button type="button" onClick={ accessDomNodes }>
            I'm sure the DOM node exists now
        </button>
        <div>found children: { childsList.length }</div>
    </div>);
};

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...