我想在单击按钮时在Home.js中获取div的文本...我已经设置了createContext();
我尝试使用Refs无效。.所以现在我正在尝试createContext()...在themeContext.js中,我有一个handleChange函数,当单击该函数时,该函数将传递给Button.js,我只想Home.js中div的文本内容。
Index.js:
import React from "react";
import ReactDOM from "react-dom";
import { ThemeContextProvider } from "./themeContext";
import App from "./App";
const RootElement = document.getElementById("root");
ReactDOM.render(
<ThemeContextProvider>
<App />
</ThemeContextProvider>,
RootElement
);
themeContext.js:
import React, { Component } from "react";
const { Provider, Consumer } = React.createContext();
class ThemeContextProvider extends Component {
state = {
test: "test"
};
handleChange = () => {
this.test.textContent
};
render() {
return (
<Provider
value={{ test: this.state.test, handleChange: this.handleChange }}
>
{this.props.children}
</Provider>
);
}
}
export { ThemeContextProvider, Consumer as ThemeContextConsumer };
Button.js:
import React from "react";
import { ThemeContextConsumer } from "./themeContext";
export default function Button(props) {
return (
<>
<ThemeContextConsumer>
{context => <button onClick={context.handleChange}>ooMe</button>}
</ThemeContextConsumer>
</>
);
}
Home.js:
import React from "react";
import { ThemeContextConsumer } from "./themeContext";
import Button from "./Button";
export default function Home(props) {
return (
<>
<ThemeContextConsumer>
{context => (
<>
<div className={context.test}>You Exposed Me!</div>
<br />
<h4>
Button From Test:
<br />
<Button handleChange={context.handleChange} />
</h4>
</>
)}
</ThemeContextConsumer>
</>
);
}
App.js
import React from "react";
import "./styles.css";
import Home from "./Home";
import Another from "./Another";
export default function App() {
return (
<div className="App">
<Home />
<Another />
</div>
);
}
如果您的意图只是获取元素值,则可以为此使用引用。
function App() {
const divRef = React.useRef(null);
function handleClick() {
console.log(divRef.current.textContent);
}
return (
<div>
<div ref={divRef} onClick={handleClick}>
Foo
</div>
<Button onClick={handleClick} />
</div>
);
}
function Button({ onClick }) {
return <button onClick={onClick}>Click me</button>
}
ReactDOM.render(<App />, document.getElementById("root"));
<script src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<div id="root" />
当您首先检查要尝试的库的基本步骤时,这很简单。有很多像样的文档。
此外,如果您要使用React,我强烈建议您以React的方式思考。您不会看到许多代码试图像这样获取元素的值。