#java #reactjs #switch-statement #command #toggle
Вопрос:
Я пытаюсь связать переключатели с различными действиями, которые я хочу выполнить, и у меня возникли некоторые проблемы с тем, как связать состояние, в которое они переключены, для выполнения определенной команды. Наконец-то я заставил их появиться в React и функционировать без привязанной к ним реальной команды. Теперь я немного запутался в том, как это сделать. я свяжу все, что у меня есть ниже. Если бы вы могли показать мне, как и лучший/типичный способ сделать это, я был бы признателен.
App.js:
import React, { Component } from 'react'; import styled from "styled-components"; import server_config from "./config/machine_specific_server_config.json"; import Switch from 'react-switch'; import ToggleSwitch from "./Switch/ToggleSwitch"; import './App.css' const ButtonGroup = styled.div` display: flex; padding: 20px 60px; margin: 10px; justify-content: center; align-items: center; ` const Button = styled.button` background-color: black; color: white; font-size: 15px; padding: 10px 30px; border-radius: 5px; margin: 10px 10px; cursor: pointer; `; const AxisLabelHeader = styled.div` display: flex; justify-content:center; // centers in the flex direction and the default flex-direction is row align-items:center; // centers perpendicular to the flex direction //height: 100vh; // 100% view height width: 100vw; // 100% view width position: absolute; // so it goes behind the current content color:black; font-weight:bold; font-family: Arial, Helvetica, sans-serif; font-size: 40px; `; class App extends Component { constructor () { super(); this.handleClick = this.handleClick.bind(this); this.connect = this.connect.bind(this); this.state = { x_position: 0, y_position: 0, z_position: 0, c_position: 0 } } connect() { const client = new WebSocket('ws://' server_config.SERVER_ADDRESS ':' server_config.SERVER_PORT '/ws'); client.onmessage = this.onMessage; client.onerror = this.onError; client.onclose = this.onClose; this.setState({ client: client, }) } componentDidMount() { this.connect(); } componentWillUnmount() { const {client, interval} = this.state; client.close() //clearInterval(interval) } onMessage = (ev) =gt; { console.log(ev.data); const recv = JSON.parse(ev.data); for (var key in recv) { this.setState({ [key]: recv[key] }) }; } onError = (error) =gt; { console.error("websocket error: " error.message); } onClose = (e) =gt; { console.log('Socket is closed. Reconnect will be attempted in 1 second.', e.reason); setTimeout(this.connect(), 1000); } handleMachineStateCommand(command) { console.log("Machine command is " command); const requestOptions = { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ "state": command }) }; function handleError (response) { console.log('response ' response.ok); if (!response.ok) { throw Error(response.statusText) } return response; } fetch('http://' server_config.SERVER_ADDRESS ':' server_config.SERVER_PORT '/machine/state', requestOptions) .then(handleError) .then(function(response) { console.log(response.success_string) console.log("ok"); }) .catch(function(error) { console.log(error) }) } handleMachineDriveCommand(command) { console.log("Machine command is " command); const requestOptions = { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ "state": command }) }; function handleError (response) { console.log('response ' response.ok); if (!response.ok) { throw Error(response.statusText) } return response; } fetch('http://' server_config.SERVER_ADDRESS ':' server_config.SERVER_PORT '/machine/' command, requestOptions) .then(handleError) .then(function(response) { console.log(response.success_string) console.log("ok"); }) .catch(function(error) { console.log(error) }) } handleClick (jog_axis, jog_amount) { console.log('Success!'); console.log('Jog axis is ' jog_axis ' and jog amount is ' jog_amount.toString()); const requestOptions = { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ "target_position": 0 }) }; function handleError (response) { console.log('response ' response.ok); if (!response.ok) { throw Error(response.statusText) } return response; } requestOptions.body = JSON.stringify({ "target_position": jog_amount }) fetch('http://' server_config.SERVER_ADDRESS ':' server_config.SERVER_PORT '/axes/' jog_axis.toLowerCase() '/motion/relative', requestOptions) .then(handleError) .then(function(response) { console.log(response.success_string) console.log("ok"); }) .catch(function(error) { console.log(error) }) } //Gripper// handleMachineGripperCommand(command) { console.log("Machine command is " command); const requestOptions = { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ "gripper_state": command }) }; function handleError (response) { console.log('response ' response.ok); if (!response.ok) { throw Error(response.statusText) } return response; } fetch('http://' server_config.SERVER_ADDRESS ':' server_config.SERVER_PORT '/machine/gripper', requestOptions) .then(handleError) .then(function(response) { console.log(response.success_string) console.log("ok"); }) .catch(function(error) { console.log(error) }) } //Tool Clamping State// handleMachineToolCommand(command) { console.log("Machine command is " command); const requestOptions = { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ "point_state": command }) }; function handleError (response) { console.log('response ' response.ok); if (!response.ok) { throw Error(response.statusText) } return response; } fetch('http://' server_config.SERVER_ADDRESS ':' server_config.SERVER_PORT '/axes/x/io/output/0', requestOptions) .then(handleError) .then(function(response) { console.log(response.success_string) console.log("ok"); }) .catch(function(error) { console.log(error) }) } //Air Connect// handleMachineAirConnectCommand(command) { console.log("Machine command is " command); const requestOptions = { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ "point_state": command }) }; function handleError (response) { console.log('response ' response.ok); if (!response.ok) { throw Error(response.statusText) } return response; } fetch('http://' server_config.SERVER_ADDRESS ':' server_config.SERVER_PORT '/axes/x/io/output/1', requestOptions) .then(handleError) .then(function(response) { console.log(response.success_string) console.log("ok"); }) .catch(function(error) { console.log(error) }) } ////Test Start//// //// Toggle Switch //// ////Test End//// //// --UI-- //// render () { return ( lt;div className='button__container'gt; lt;AxisLabelHeadergt;Positionslt;/AxisLabelHeadergt; lt;brgt;lt;/brgt; lt;table class="centerTable"gt; lt;trgt; lt;td class="centerTableCell"gt;X: {this.state.x_position.toFixed(4)}lt;/tdgt; lt;td class="centerTableCell"gt;Y: {this.state.y_position.toFixed(4)}lt;/tdgt; lt;td class="centerTableCell"gt;Z: {this.state.y_position.toFixed(4)}lt;/tdgt; lt;td class="centerTableCell"gt;C: {this.state.y_position.toFixed(4)}lt;/tdgt; lt;/trgt; lt;/tablegt; lt;AxisLabelHeadergt;Machinelt;/AxisLabelHeadergt; lt;brgt;lt;/brgt; lt;ButtonGroupgt; lt;Button onClick={() =gt; this.handleMachineStateCommand("abort")}gt; ABORT lt;/Buttongt; lt;Button onClick={() =gt; this.handleMachineStateCommand("stop")}gt; STOP lt;/Buttongt; lt;Button onClick={() =gt; this.handleMachineStateCommand("manual")}gt; MANUAL lt;/Buttongt; lt;/ButtonGroupgt; lt;AxisLabelHeadergt;Driveslt;/AxisLabelHeadergt; lt;brgt;lt;/brgt; lt;ButtonGroupgt; lt;Button onClick={() =gt; this.handleMachineDriveCommand("reset")}gt; RESET ALL lt;/Buttongt; lt;Button onClick={() =gt; this.handleMachineDriveCommand("enable")}gt; ENABLE ALL lt;/Buttongt; lt;/ButtonGroupgt; lt;AxisLabelHeadergt;Switch Testlt;/AxisLabelHeadergt; lt;brgt;lt;/brgt; lt;brgt;lt;/brgt; lt;React.Fragmentgt; lt;ToggleSwitch label="Test_1" /gt; lt;ToggleSwitch label="Test_2" /gt; lt;/React.Fragmentgt; lt;brgt;lt;/brgt; lt;AxisLabelHeadergt;Gripperlt;/AxisLabelHeadergt; lt;brgt;lt;/brgt; lt;ButtonGroupgt; lt;Button onClick={() =gt; this.handleMachineGripperCommand("open")}gt; OPEN lt;/Buttongt; lt;Button onClick={() =gt; this.handleMachineGripperCommand("close")}gt; CLOSE lt;/Buttongt; lt;/ButtonGroupgt; lt;brgt;lt;/brgt; lt;ButtonGroupgt; lt;Button onClick={() =gt; this.handleMachineToolCommand("0")}gt; TOOL CLAMP lt;/Buttongt; lt;Button onClick={() =gt; this.handleMachineToolCommand("1")}gt; TOOL UNCLAMP lt;/Buttongt; lt;/ButtonGroupgt; lt;AxisLabelHeadergt;Air Connectlt;/AxisLabelHeadergt; lt;brgt;lt;/brgt; lt;ButtonGroupgt; lt;Button onClick={() =gt; this.handleMachineAirConnectCommand("0")}gt; DISENGAGE lt;/Buttongt; lt;Button onClick={() =gt; this.handleMachineAirConnectCommand("1")}gt; ENGAGE lt;/Buttongt; lt;/ButtonGroupgt; lt;AxisLabelHeadergt;X Axislt;/AxisLabelHeadergt; lt;brgt;lt;/brgt; lt;ButtonGroupgt; lt;Button onClick={() =gt; this.handleClick("x", 10.0)}gt; Jog 10mm lt;/Buttongt; lt;Button onClick={() =gt; this.handleClick("x", -10.0)}gt; Jog -10mm lt;/Buttongt; lt;/ButtonGroupgt; lt;AxisLabelHeadergt;Z Axislt;/AxisLabelHeadergt; lt;brgt;lt;/brgt; lt;ButtonGroupgt; lt;Button onClick={() =gt; this.handleClick("z", 10.0)}gt; Jog 10mm lt;/Buttongt; lt;Button onClick={() =gt; this.handleClick("z", -10.0)}gt; Jog -10mm lt;/Buttongt; lt;/ButtonGroupgt; lt;AxisLabelHeadergt;C Axislt;/AxisLabelHeadergt; lt;brgt;lt;/brgt; lt;ButtonGroupgt; lt;Button name="Cplus" onClick={() =gt; this.handleClick("c", 1.0)}gt; Jog 1deg lt;/Buttongt; lt;Button onClick={() =gt; this.handleClick("c", -1.0)}gt; Jog -1deg lt;/Buttongt; lt;/ButtonGroupgt; lt;/divgt; ) } } export default App
ToggleSwitch.js:
import React from "react"; import "./ToggleSwitch.css"; const ToggleSwitch = ({ label }) =gt; { return ( lt;div className="container"gt; {label}{" "} lt;div className="toggle-switch"gt; lt;input type="checkbox" className="checkbox" name={label} id={label} /gt; lt;label className="label" htmlFor={label}gt; lt;span className="inner" /gt; lt;span className="switch" /gt; lt;/labelgt; lt;/divgt; lt;/divgt; ); }; export default ToggleSwitch;
ToggleSwitch.css:
.container { text-align: center; } .toggle-switch { position: relative; width: 75px; display: inline-block; text-align: left; top: 8px; } .checkbox { display: none; } .label { display: block; overflow: hidden; cursor: pointer; border: 0 solid #bbb; border-radius: 20px; } .inner { display: block; width: 200%; margin-left: -100%; transition: margin 0.3s ease-in 0s; } .inner:before, .inner:after { float: left; width: 50%; height: 36px; padding: 0; line-height: 36px; color: #fff; font-weight: bold; box-sizing: border-box; } .inner:before { content: "ON"; padding-left: 10px; background-color: #03ff36; color: #fff; } .inner:after { content: "OFF"; padding-right: 10px; background-color: #ff0307; color: #fff; text-align: right; } .switch { display: block; width: 24px; margin: 5px; background: #fff; position: absolute; top: 0; bottom: 0; right: 40px; border: 0 solid #bbb; border-radius: 20px; transition: all 0.3s ease-in 0s; } .checkbox:checked .label .inner { margin-left: 0; } .checkbox:checked .label .switch { right: 0px; }