我是编码的新手,我想向我的AddWord.jsx显示Form.jsx。Form.jsx是Addword.jsx表单,是Addword.js onclick中的按钮,我必须显示Form.jsx 帮帮我
//This is my code
import React from 'react'
import App from '../App'
import Form from './Form'
function AddWords() {
return (
<div>
<button type="button" onclick="">Click Me!</button>
</div>
)
}
export default AddWords
答案 0 :(得分:0)
稍微重新排列代码,以便可以使用可重用的按钮组件,并在其中放置表单和按钮的父组件(App
)。
在此示例中,表单可见性以App
状态存储(使用the useState
React hook),并且按钮处理程序向下传递到其props中的按钮以切换该状态true
/ {{ 1}},显示/隐藏表格。
false
// This example uses the the `useState` hook for
// storing state
const { useState, Fragment } = React;
// A simple form component
function Form() {
return <div>Form</div>;
}
// AddWords is now a reusable button component
// that accepts a button handler function, and some text
// for the button. When `onClick` (don't forget that
// it's camelCase) is called it calls the handler
// that was passed down to it.
function Button({ handleButton, text }) {
return (
<div>
<button
type="button"
onClick={handleButton}
>
{text}
</button>
</div>
);
}
function App() {
// Initialise the state to false. `isFormVisible` is the
// variable that holds the state, `setFormVisible` is the
// function that allows us to update it.
const [ isFormVisible, setFormVisible ] = useState(false);
// The handler that we pass to the button. It toggles
// the `isFormVisible` state from `true` to `false`, or
// `false` to `true.
function toggleForm() {
setFormVisible((visible) => !visible);
}
// We return a fragment wrapping our child
// Form and Button components. Note that we're
// passing the toggleForm function and text down as
// Button props.
// The form is only visible if `isFormVisible` is true.
return (
<Fragment>
<Button
handleButton={toggleForm}
text="Click me!"
/>
{isFormVisible && <Form />}
</Fragment>
);
}
// Render it
ReactDOM.render(
<App />,
document.getElementById('root')
);
答案 1 :(得分:0)
您可以将功能组件转换为类组件,并且代码将更加精确和易读。在这里,我使用了 state
,它绑定了此react应用程序,如果任何更改,则dom元素将根据更改呈现。
我还要在这里提到的另一件事是 {this.state.isVisible && <Form />}
,在javascript中,如果第一部分返回true,则下一部分将不执行,否则,如果 this.state.isVisible
= true,只有 Form
可见
import React, { Component } from "react";
import Form from "./Form";
class AddWords extends Component {
state = {
isVisible: false
};
handleClick = () => {
this.setState({ isVisible: true });
};
render() {
return (
<div>
<h1>AddWords</h1>
<button onClick={this.handleClick}>Click Me!</button>
{this.state.isVisible && <Form />}
</div>
);
}
}
export default AddWords;