如何在Gatsby React项目中用自定义Button组件嵌入Typeform?
Great question! You're on the right track wanting to keep your site's theme consistent by using your custom Button component instead of the plain HTML button. Here's how to adjust your code to make this work smoothly, following React best practices:
Step 1: Import Your Custom Button Component
First, make sure you import your Button component into the ContactInfo component. Replace the path with the actual location of your Button file:
import Button from './path-to-your-button-component'; // e.g., '../components/Button'
Step 2: Refactor the Popup Logic to Use React's Event Handling
Instead of manually querying the DOM with getElementById to attach a click listener, we'll store the Typeform popup instance on the component itself, then bind the open action directly to your custom Button's onClick prop. This is much cleaner and aligns with React's paradigm.
Full Modified ContactInfo Component
Here's the updated code for your ContactInfo class component:
import React, { Component } from 'react'; import * as typeformEmbed from '@typeform/embed'; import Button from './path-to-your-button-component'; // Update this path class ContactInfo extends Component { componentDidMount() { // Store the popup instance on the component so we can access it in render this.popup1 = typeformEmbed.makePopup('YOUR_TYPEFORM_URL', { mode: 'drawer_right', autoclose: 3000, hideHeaders: true, onSubmit: () => { console.log('Typeform successfully submitted'); } }); } render() { return ( <div> {/* Use your custom Button component and bind the click handler */} <Button primary block onClick={() => this.popup1.open()} > Popup </Button> </div> ); } } export default ContactInfo;
Optional: Add onClick Prop Type to Your Custom Button
While styled-components automatically passes through native event props like onClick, it's good practice to explicitly define it in your Button's prop types for clarity and type safety. Update your Button component like this:
import React from 'react'; import PropTypes from 'prop-types'; import * as Styled from './styles'; const Button = ({ primary, block, onClick, children }) => ( <Styled.Button primary={primary} block={block} onClick={onClick} // Explicitly pass the onClick handler whileHover={{ scale: 1.05 }} whileTap={{ scale: 0.95 }} > {children} </Styled.Button> ); Button.propTypes = { primary: PropTypes.bool, block: PropTypes.bool, onClick: PropTypes.func, // Add this line children: PropTypes.any.isRequired }; export default Button;
Why This Works
- By storing the popup instance as
this.popup1, we can easily reference it in theonClickhandler without touching the DOM directly. - Your custom Button component will retain all its styled features (hover/tap animations, primary/block variants) while triggering the Typeform popup when clicked.
内容的提问来源于stack exchange,提问作者clattenburg cake

