Попытка обновить цветовой ключ состояния контекста на основе ввода идентификатора элемента "textToColor".
setColor("yellow")
работает нормально setColor("blue")
не работает, поскольку выполняется в функции returnInput. setColor(document.getElementById('textToColor').value);
То же, что и выше, и также не работает в возврате, где setColor("yellow") works.
Приложение. js
import * as React from "react";
import { ContextOne } from "./ContextOne";
export function App() {
// [A]
let { state, dispatch } = React.useContext(ContextOne);
// [B]
React.useEffect(
() => {
document.body.style.backgroundColor = state.currentColor;
},
[state.currentColor]
);
// [C]
let inc = () => dispatch({ type: "increment" });
let dec = () => dispatch({ type: "decrement" });
let reset = () => dispatch({ type: "reset" });
let setColor = color => () => dispatch({ type: "set-color", payload: color });
let returnInput = () => {
console.log('In return input');
console.log(document.getElementById('textToColor').value);
setColor("blue");
//^^^ Doesn't work
//setColor(document.getElementById('textToColor').value);
//^^^ Doesn't work
}
return (
<React.Fragment>
<div style={{ textAlign: "center" }}>
<p>
Current color is: <b>{state.currentColor}</b>
</p>
<p>
Current count: <b>{state.count}</b>
</p>
</div>
<div style={{ paddingTop: 40 }}>
<p>Count controls:</p>
<button onClick={inc}>Increment!</button>
<button onClick={dec}>Decrement!</button>
</div>
<div>
<p>Color controls:</p>
<input id="textToColor" />
<button onClick={() => returnInput()}>Change to input color</button>
<button onClick={setColor("yellow")}>Change to papayawhip!</button>
</div>
<div>
<p>Reset changes:</p>
<button onClick={reset}>Reset!</button>
</div>
</React.Fragment>
);
}
ContextOne. js
import * as React from "react";
let ContextOne = React.createContext();
let initialState = {
count: 10,
currentColor: "#bada55"
};
let reducer = (state, action) => {
switch (action.type) {
case "reset":
return initialState;
case "increment":
return { ...state, count: state.count + 1 };
case "decrement":
return { ...state, count: state.count - 1 };
case "set-color":
return { ...state, currentColor: action.payload };
}
};
function ContextOneProvider(props) {
// [A]
let [state, dispatch] = React.useReducer(reducer, initialState);
let value = { state, dispatch };
// [B]
return (
<ContextOne.Provider value={value}>{props.children}</ContextOne.Provider>
);
}
let ContextOneConsumer = ContextOne.Consumer;
// [C]
export { ContextOne, ContextOneProvider, ContextOneConsumer };