我想对Formik <Field/>
进行反跳,但是当我在该字段中键入内容时,似乎反跳不起作用。我也尝试过lodash.debounce,油门反跳和相同的结果。该如何解决?
CodeSandbox -https://codesandbox.io/s/priceless-nobel-7p6nt
代码段:
import ReactDOM from "react-dom";
import { withFormik, Field, Form } from "formik";
const App = ({ setFieldValue }) => {
let timeout;
const [text, setText] = useState("");
const onChange = text => {
if (timeout) clearTimeout(timeout);
timeout = setTimeout(() => setText(text), 750);
};
return (
<Form>
<Field
type="text"
name="textField"
placeholder="Type something..."
onChange={e => {
onChange(e.target.value);
setFieldValue("textField", e.target.value);
}}
style={{ width: "100%" }}
/>
<br />
<br />
<div>output: {text}</div>
</Form>
);
};
const Enhanced = withFormik({
mapPropsToValues: () => ({
textField: ""
}),
handleSubmit: (values, { setSubmitting }) => {
setSubmitting(false);
return false;
}
})(App);
ReactDOM.render(<Enhanced />, document.getElementById("root"));
答案 0 :(得分:1)
const [text, setText] = useState("");
const [t, setT] = useState(null);
const onChange = text => {
if (t) clearTimeout(t);
setT(setTimeout(() => setText(text), 750));
};
答案 1 :(得分:1)
我建议将呼叫移至超时功能内。
<div id="app">
<div id="rows">
<div class="row" v-for="row in rows" v-bind:style="{ top: row.top + 'px' }">
{{row.id}}
</div>
</div>
</div>
<script>
const app = new Vue({
el: '#app',
data() {
return {
rows: []
}
},
created() {
for (let i = 0; i < 30; i++) {
this.rows.push({
id: i,
top: i * 40
})
}
setInterval(() => {
window.requestAnimationFrame(this.update);
}, 16);
},
methods: {
update() {
this.rows.forEach(row => {
row.top -= 0.5
});
if (this.rows[0].top <= -40) {
this.rows.push({
id: this.rows[0].id,
top: (this.rows.length - 1) * 40
})
this.rows.shift();
}
}
}
})
</script>
<style>
#rows {
position: relative;
}
.row {
position: absolute;
width: 100%;
height: 40px;
border: 1px solid black;
}
</style>